<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Validate;
use app\admin\common\Constants;
use AntCloudSDKCore\AntCloudClient;
use think\Log;
use think\Queue;
use QRcode;

header("Content-type: text/html; charset=utf-8");
header('Access-Control-Allow-Origin: *');

class App extends Controller
{

    public function index()
    {
        //公司ID
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID不能为空');
        }
        //首页轮播图取公司介绍的轮播图
        $imgs = db('company_introduction')->where(['id' => $company_id])->value('imgs');
        if ($imgs) {
            $img = explode(',', $imgs);
            foreach ($img as $k => $v) {
                $banner[$k] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where("id=$v")->value('path');
            }
        }


        //最新资讯
        $news = db('news_information')->order('sort desc,create_time desc')->field('id,title,img,create_time')->limit(0, 3)->select();
        foreach ($news as $k => $v) {
            if ($v['img']) {
                $news[$k]['img'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $v['img']])->value('path');
            }
            $news[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);

        }
        $data['role'] = db('staff')->where(['company_id' => $company_id, 'uid' => $_POST['uid']])->value('role');
        $banner ? $data['banner'] = $banner : [];
        $news ? $data['news'] = $news : [];
        $condition['uid'] = $_POST['uid'];
        $condition['status'] = array('lt', 3);//小于3  统计提交中跟审核中的
        $condition['company_id'] = $_POST['company_id'];
        $data['apply_count'] = db('app_form')->where($condition)->count();
        $where['uid'] = $_POST['uid'];
        $where['company_id'] = $_POST['company_id'];
        $where['status'] = array('eq', 1);
        $data['examine_count'] = db('approval_process')->group('form_id')->where($where)->count();
        return apireturn(1, '成功', $data);
    }

    //删除印章
    public function del_seal()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '对象ID为空');
        }
        $res = db('seal')->where(['id' => $id])->update(['is_del' => 1]);
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    //提交申请回显(还没提交，只是页面回显)(已弃用)
    public function submit_application_echo123()
    {
        //得到公司ID，用户ID，看他属于哪些部门，然后显示对应的印章
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID不能为空');
        }
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID不能为空');
        }
        $list = db('staff')->where(array('uid' => $uid, 'company_id' => $company_id))->field('department_id')->select();
        foreach ($list as $k => $v) {
            $department_id .= ',' . $v['department_id'];
        }

        $department = substr($department_id, 1);

        $d_list = explode(',', $department);
        foreach ($d_list as $k => $v) {
            $seal_id .= ',' . db('seal')->where(['department' => $v])->value('id');
        }
        //印章ID集合
        $seal = substr($seal_id, 1);

        if ($seal) {
            $seals = explode(',', $seal);
            foreach ($seals as $k => $v) {
                $sealss[$k]['id'] = $v;
                $sealss[$k]['name'] = db('seal')->where(['id' => $v])->value('name');
            }
            return apireturn(1, '成功', $sealss);
        } else {
            return apireturn(2, '没有对应部门', []);
        }
    }

    //提交申请回显(还没提交，只是页面回显)
    public function submit_application_echo()
    {

        //得到公司ID，用户ID，看他属于哪些部门，然后显示对应的印章
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID不能为空');
        }
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID不能为空');
        }


        //用户所属部门ID集合
        $department_list = db('staff')->where(array('uid' => $uid, 'company_id' => $company_id))->value('department_id');

        if ($department_list == 1) {
            $p_list = db('department')->where(['company_id' => $company_id])->field('id')->select();
            foreach ($p_list as $k => $v) {
                $lp .= ',' . $v['id'];
            }
            $department_list = substr($lp, 1);

        }


        $id_list = explode(',', $department_list);
        //这个公司所有的印章ID集合
        $seal_list = db('seal')->where(array('company_id' => $company_id, 'is_del' => 0))->order('id desc')->select();
        foreach ($seal_list as $k => $v) {
            //印章所属部门ID集合
            $list = explode(',', $v['department']);
            //判断两个数组之间有没有相同的值
            $res = array_intersect($list, $id_list);
            if ($res) {
                //存在的话就说明印章跟用户之间有相同部门，可以申请这个印章
                $seal_id .= ',' . $v['id'];
            }
        }

        $info = db('app_form')->where(['uid' => $uid])->order('id desc')->value('seal_id');
        $type_id = db('app_form')->where(['uid' => $uid])->order('id desc')->value('app_id');

        $is_free = db('approval')->where(['id' => $type_id])->value('is_free');
        if ($is_free == 2) {
            // $iid=db('app_form')->where(['uid'=>$uid])->order('id desc')->value('id');
            // // $data['uuid']=db('approval_process')->where(['form_id'=>$iid])->value('uid');
            // // $data['uname']=db('user')->where(['id'=>$data['uuid']])->value('username');
            // $ulist=db('approval_process')->where(['form_id'=>$iid])->field('uid')->order('id asc')->select();
            // foreach($ulist as $k=>$v){
            //     $b.=','.$v['uid'];
            //     $bname.='/'.db('user')->where(['id'=>$v['uid']])->value('username');
            // }
            // $data['uuid']=substr($b,1);
            // $data['uname']=substr($bname,1);
            $data['free'] = '111';
            $data['uuid'] = '';
            $data['uname'] = '';
        } else {
            $data['free'] = '';
            $data['uuid'] = '';
            $data['uname'] = '';
        }

        //印章ID集合
        $seal = substr($seal_id, 1);

        if ($seal) {
            $seals = explode(',', $seal);
            foreach ($seals as $k => $v) {
                // $sealss[$k]['id']=$v;
                //$sealss[$k]=db('seal')->where(['id'=>$v])->value('name');
                $sealss_name = db('seal')->where(['id' => $v])->value('name');


                // $len=mb_strlen($sealss_name,'utf-8');
                // if($len>14){
                // 	$sealss[$k]=mb_substr($sealss_name,0,14,'utf-8').'...';
                // }else{
                $sealss[$k] = $sealss_name;
                // }

                $seall[$k]['id'] = $v;

            }

            $ids = array_column($seall, 'id');
            //当前ID的下标值
            $key = array_search($info, $ids);
            //print_r($seall);die;
            $data['list'] = $sealss;
            $data['key'] = $key;//上次选中印章的下标


            $seal_id = $seals[$key];

            $list = db('approval')->where(['seal_id' => $seal_id, 'is_del' => 0])->field('id,type_name')->order('id desc')->select();

            if ($list) {
                $data['seal_id'] = $seal_id;
                foreach ($list as $k => $v) {
                    $bb .= ',' . $v['type_name'];
                }
                $l = substr($bb, 1);

                $ids = array_column($list, 'id');
                //当前ID的下标值
                $key = array_search($type_id, $ids);
                $data['index123'] = $key;
                $data['type_id'] = $type_id;

                $data['l'] = explode(',', $l);
                $data['type_list'] = $list;
            }


            return apireturn(1, '成功', $data);
        } else {
            return apireturn(2, '没有对应部门', []);
        }
    }

    //选中印章之后，显示对应的审批类型
    public function approval_type()
    {
        // $seal_id=$_POST['seal_id'];;
        // if(!$seal_id){
        //     return apireturn(2,'印章ID不能为空');
        // }
        $subscript = $_POST['subscript'];
        if (is_numeric($subscript) === false) {
            //获取下标去处理
            if (!$subscript) {
                return apireturn(2, '对象不能为空');
            }
        }


        //得到公司ID，用户ID，看他属于哪些部门，然后显示对应的印章
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID不能为空');
        }
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID不能为空');
        }


        //用户所属部门ID集合
        $department_list = db('staff')->where(array('uid' => $uid, 'company_id' => $company_id))->value('department_id');

        if ($department_list == 1) {
            $p_list = db('department')->where(['company_id' => $company_id])->field('id')->select();
            foreach ($p_list as $k => $v) {
                $lp .= ',' . $v['id'];
            }
            $department_list = substr($lp, 1);
            //print_r($department_list);die;
        }


        $id_list = explode(',', $department_list);
        //这个公司所有的印章ID集合
        $seal_list = db('seal')->where(array('company_id' => $company_id, 'is_del' => 0))->order('id desc')->select();
        //print_r($seal_list);die;
        foreach ($seal_list as $k => $v) {
            //印章所属部门ID集合
            $list = explode(',', $v['department']);
            //判断两个数组之间有没有相同的值
            $res = array_intersect($list, $id_list);
            if ($res) {
                //存在的话就说明印章跟用户之间有相同部门，可以申请这个印章
                $seal_ids .= ',' . $v['id'];
            }
        }


        //印章ID集合
        $seal = substr($seal_ids, 1);
        $seal_array = explode(',', $seal);
        $seal_id = $seal_array[$subscript];
        // print_r($seal_id);die;
        //print_r($seal_id);die;

        $list = db('approval')->where(['seal_id' => $seal_id, 'is_del' => 0])->field('id,type_name')->order('id desc')->select();
        if ($list) {
            $data['seal_id'] = $seal_id;
            foreach ($list as $k => $v) {
                $bb .= ',' . $v['type_name'];
            }
            $l = substr($bb, 1);
            $data['l'] = explode(',', $l);
            $data['list'] = $list;
            return apireturn(1, '成功', $data);
        } else {
            $data['seal_id'] = $seal_id;
            $data['l'] = [];
            $data['list'] = array(array('id' => 0));
            return apireturn(2, '审批类型不能为空', $data);
        }
    }

    //提交申请
    public function submit_application()
    {
        $company_id = $_POST['company_id'];
        //用户ID也就是申请人ID
        $data['uid'] = $_POST['uid'];
        if (!is_numeric($data['uid'])) {
            return apireturn(2, '申请人ID为空或者格式错误');
        }
        $data['lng'] = $_POST['lng'];
        $data['lat'] = $_POST['lat'];
        /*if (!$data['lng'] || !$data['lat']) {
            return apireturn(2, '请打开小程序定位');
        }*/
        //印章ID
        $data['seal_id'] = $_POST['seal_id'];
        if (!is_numeric($data['seal_id'])) {
            return apireturn(2, '印章ID不能为空或者格式错误');
        }
        //审批类型ID
        $data['app_id'] = $_POST['app_id'];
        if (!$_POST['app_id']) {
            return apireturn(2, '审批类型不能为空或者格式错误');
        }
        if (!is_numeric($data['app_id'])) {
            return apireturn(2, '审批类型不能为空或者格式错误');
        }


        //文件名称
        $data['name'] = $_POST['name'];
        if (!$data['name'] || $data['name'] == 'undefined') {
            return apireturn(2, '文件名称不能为空');
        }
        //文件编号
        $data['number'] = $_POST['number'];
        //if(!$data['number']){
        //    return apireturn(2,'文件编号不能为空');
        //}
        //用章次数
        $data['frequency'] = $_POST['frequency'];
        if (!is_numeric($data['frequency'])) {
            return apireturn(2, '用章次数不能为空或者格式错误');
        }
        //剩余次数就是用章次数，不过要等审核通过之后才会有用
        $data['remaining_times'] = $_POST['frequency'];
        //图片
        $data['imgs'] = $_POST['imgs'];
        //if(!$data['imgs']){
        //    return apireturn(2,'上传图片不能为空');
        //}
        //备注
        $data['remark'] = $_POST['remark'];
        //if(!$data['remark']){
        //   return apireturn(2,'备注不能为空');
        //}
        //申请文档 我觉得上传到本地了，是个地址
        $data['file'] = $_POST['file'];
        //if(!$data['file']){
        //    return apireturn(2,'申请文档不能为空');
        //}
        $data['create_time'] = time();

        $data['company_id'] = $_POST['company_id'];

        $app_id = $_POST['app_id'];
        //审批流程

        $is_free = db('approval')->where(['id' => $app_id])->value('is_free');
        if ($is_free == 2) {
            file_put_contents('38.txt', $_POST['uuid']);
            if (!$_POST['uuid']) {
                return apireturn(2, '审批人不能为空');
            }
        }
        $res = db('app_form')->insertGetId($data);
        if ($res) {
            //提交成功我就添加审核流程
            //审批类型ID

            if ($is_free == 2) {
                //是自由审批流程
                //$add_data['uid']=$_POST['uuid'];

                //$add_data['form_id']=$res;
                //$add_data['create_time']=time();
                //$add_data['company_id']=$_POST['company_id'];


                //$uid=$_POST['uid'];
                //$openid=db('user')->where(['id'=>$_POST['uuid']])->value('app_openid');

                //$this->send_subscribe($openid,$uid,$res);

                //$add_data['status']=1;
                //db('approval_process')->insert($add_data);

                $u_list = explode(',', $_POST['uuid']);
                foreach ($u_list as $k => $v) {
                    $add_data['uid'] = $v;
                    $add_data['form_id'] = $res;
                    $add_data['create_time'] = time();
                    $add_data['company_id'] = $_POST['company_id'];
                    if ($k == 0) {
                        //轮到他审批，第一个人是当前审批人
                        $uid = $v;
                        $openid = db('user')->where(['id' => $v])->value('app_openid');
                        $this->send_subscribe($openid, $uid, $res);

                        $add_data['status'] = 1;
                    } else {
                        $add_data['status'] = 4;
                    }
                    db('approval_process')->insertGetId($add_data);
                }

            } else {
                $app_list = db('approver')->where(['app_id' => $app_id])->order('sort asc')->select();
                foreach ($app_list as $k => $v) {
                    $add_data['uid'] = $v['uid'];
                    $add_data['form_id'] = $res;
                    $add_data['create_time'] = time();
                    $add_data['company_id'] = $_POST['company_id'];
                    if ($k == 0) {
                        //轮到他审批，第一个人是当前审批人
                        $uid = $_POST['uid'];
                        $openid = db('user')->where(['id' => $v['uid']])->value('app_openid');

                        /**
                         * TODO: 发送模板消息（用章申请提醒）
                         * */
                        $this->send_subscribe($openid, $uid, $res);

                        $add_data['status'] = 1;
                    } else {
                        $add_data['status'] = 4;
                    }
                    db('approval_process')->insert($add_data);
                }
            }


            return apireturn(1, '成功', $res);
        } else {
            return apireturn(2, '失败');
        }
    }

    //我的申请页面  已弃用
    public function my_application123()
    {
        $uid = $_POST['uid'];
        if (!is_numeric($uid)) {
            return apireturn(2, '用户ID为空或者格式错误');
        }
        $company_id = $_POST['company_id'];
        if (!is_numeric($company_id)) {
            return apireturn(2, '公司ID为空或者格式错误');
        }
        //status 1:提交中 2：审核中 3：已拒绝 4：审核完成 5用章完成
        $status = $_POST['status'];

        if (!$status) {
            // print_r($status);die;
            $list = db('app_form')->where(['uid' => $uid, 'company_id' => $company_id])->select();
        } else {
            $list = db('app_form')->where(['uid' => $uid, 'status' => $status, 'company_id' => $company_id])->select();
        }
        //要统计各个状态的总数量
        $data['count'] = db('app_form')->where(['uid' => $uid, 'company_id' => $company_id])->count();
        $data['submitting'] = db('app_form')->where(['uid' => $uid, 'status' => 1, 'company_id' => $company_id])->count();
        $data['under_review'] = db('app_form')->where(['uid' => $uid, 'status' => 2, 'company_id' => $company_id])->count();
        $data['rejected'] = db('app_form')->where(['uid' => $uid, 'status' => 3, 'company_id' => $company_id])->count();
        $data['audit_completed'] = db('app_form')->where(['uid' => $uid, 'status' => 4, 'company_id' => $company_id])->count();
        $data['complete_chapter'] = db('app_form')->where(['uid' => $uid, 'status' => 5, 'company_id' => $company_id])->count();

        if ($list) {
            foreach ($list as $k => $v) {
                $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                $list[$k]['seal_name'] = db('seal')->where(['id' => $v['seal_id']])->value('name');
            }
            $data['list'] = $list;
        } else {
            $data['list'] = [];
        }
        return apireturn(1, '成功', $data);
    }

    //我的申请页面
    public function my_application()
    {
        $uid = $_POST['uid'];
        if (!is_numeric($uid)) {
            return apireturn(2, '用户ID为空或者格式错误');
        }
        $company_id = $_POST['company_id'];
        if (!is_numeric($company_id)) {
            return apireturn(2, '公司ID为空或者格式错误');
        }
        //status 1:提交中 2：审核中 3：已拒绝 4：审核完成 5用章完成
        $status = $_POST['status'];

        $condition['status'] = array('gt', 4);
        $condition['uid'] = $uid;
        $condition['company_id'] = $company_id;

        if (!$status) {
            // print_r($status);die;
            $list = db('app_form')->where(['uid' => $uid, 'company_id' => $company_id])->order('id desc')->select();
        } else {
            if ($status == 5) {
                $list = db('app_form')->where($condition)->order('id desc')->select();
            } else {
                $list = db('app_form')->where(['uid' => $uid, 'status' => $status, 'company_id' => $company_id])->order('id desc')->select();
            }

        }
        //要统计各个状态的总数量
        $data['count'] = db('app_form')->where(['uid' => $uid, 'company_id' => $company_id])->count();
        $data['submitting'] = db('app_form')->where(['uid' => $uid, 'status' => 1, 'company_id' => $company_id])->count();
        $data['under_review'] = db('app_form')->where(['uid' => $uid, 'status' => 2, 'company_id' => $company_id])->count();
        $data['rejected'] = db('app_form')->where(['uid' => $uid, 'status' => 3, 'company_id' => $company_id])->count();
        $data['audit_completed'] = db('app_form')->where(['uid' => $uid, 'status' => 4, 'company_id' => $company_id])->count();
        $data['complete_chapter'] = db('app_form')->where($condition)->count();

        if ($list) {
            foreach ($list as $k => $v) {
                $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                $list[$k]['seal_name'] = db('seal')->where(['id' => $v['seal_id']])->value('name');
                if ($v['qkl']) {
                    $list[$k]['qkl_src'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $v['qkl']])->value('path');
                } else {
                    $list[$k]['qkl_src'] = '';
                }
            }
            $data['list'] = $list;
        } else {
            $data['list'] = [];
        }
        return apireturn(1, '成功', $data);
    }

    //我的审核 已弃用
    public function my_review123()
    {
        //用户ID
        $uid = $_POST['uid'];
        if (!is_numeric($uid)) {
            return apireturn(2, '用户ID为空或者格式错误');
        }
        $status = $_POST['status'];
        if (!is_numeric($status)) {
            return apireturn(2, '审核类型为空或者格式错误');
        }
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }
        //小程序status:1待审核 2：审核中  3：审批完成  4：用章完成
        if ($status == 1) {
            //待审核
            $condition['status'] = array('eq', 0);
            $condition['uid'] = $uid;
            $list = db('approval_process')->group('form_id')->where($condition)->select();
            foreach ($list as $k => $v) {
                $list[$k]['form_name'] = db('app_form')->where(['id' => $v['form_id']])->value('name');
            }
        } elseif ($status == 2) {
            //审核中 还没轮到我或者我审核完成了后面还有人没审核完成
            $where['status'] = array('neq', 0);
            $where['uid'] = $uid;
            $where['form_state'] = array('eq', 0);
            $list = db('approval_process')->group('form_id')->where($where)->select();
            foreach ($list as $k => $v) {
                $list[$k]['form_name'] = db('app_form')->where(['id' => $v['form_id']])->value('name');
            }
        } elseif ($status == 3) {
            //审批完成
            $where['uid'] = $uid;
            $where['form_state'] = array('eq', 1);
            $list = db('approval_process')->group('form_id')->where($where)->select();
            foreach ($list as $k => $v) {
                $list[$k]['form_name'] = db('app_form')->where(['id' => $v['form_id']])->value('name');
            }
        } elseif ($status == 4) {
            //用章完成
        }

        if ($list) {
            foreach ($list as $k => $v) {
                $info = db('app_form')->where(['id' => $v['form_id']])->find();
                //文件编号
                $list[$k]['number'] = $info['number'];
                //印章名称
                $list[$k]['seal_name'] = db('seal')->where(['id' => $info['seal_id']])->value('name');
                //提交时间
                $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                //状态
                if ($info['status'] == 1) {
                    $list[$k]['status_name'] = '提交中';
                } elseif ($info['status'] == 2) {
                    $list[$k]['status_name'] = '审核中';
                } elseif ($info['status'] == 3) {
                    $list[$k]['status_name'] = '已拒绝';
                } elseif ($info['status'] == 4) {
                    $list[$k]['status_name'] = '审核完成';
                } elseif ($info['status'] == 5) {
                    $list[$k]['status_name'] = '用章完成';
                }
            }
            return apireturn(1, '成功', $list);
        } else {
            return apireturn(2, '暂无', []);
        }

    }


    public function my_review()
    {
        //用户ID
        $uid = $_POST['uid'];
        if (!is_numeric($uid)) {
            return apireturn(2, '用户ID为空或者格式错误');
        }
        $status = $_POST['status'];

        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }
        //小程序status:1待审核 2：审核中  3：审批完成  4：用章完成

        $condition['uid'] = $uid;
        $condition['company_id'] = $company_id;

        //全部数量
        $count1 = db('approval_process')->group('form_id')->where($condition)->count();
        $where['uid'] = $uid;
        $where['company_id'] = $company_id;
        $where['status'] = array('eq', 1);
        $count2 = db('approval_process')->group('form_id')->where($where)->count();
        $where['status'] = array('neq', 1);
        $where['form_state'] = array('eq', 0);
        $count3 = db('approval_process')->group('form_id')->where($where)->count();
        $where['form_state'] = array('eq', 1);
        $count4 = db('approval_process')->group('form_id')->where($where)->count();
        $where['form_state'] = array('eq', 2);
        $count5 = db('approval_process')->group('form_id')->where($where)->count();
        if (!$status) {
            //全部  想分组查询找出最新的要子查询
            $comment_subquery = Db::name('approval_process')
                ->order(['id' => 'desc'])
                ->where($condition)
                ->limit(100000)//不加有可能获取的不是最新的一条
                ->buildSql();

            $list = Db::table($comment_subquery . ' a')
                ->where($condition)
                ->group('form_id')
                ->order(['id' => 'desc'])
                ->select();

            //print_r($comment_subquery);die;
            // $list=db('approval_process')->group('form_id')->where($condition)->select();

            foreach ($list as $k => $v) {
                $list[$k]['form_name'] = db('app_form')->where(['id' => $v['form_id']])->value('name');
            }
        } elseif ($status == 1) {
            //待审核
            $condition['status'] = array('eq', 1);
            // $list=db('approval_process')->group('form_id')->where($condition)->select();
            $comment_subquery = Db::name('approval_process')
                ->order('id', 'desc')
                ->limit(100000)//不加有可能获取的不是最新的一条
                ->buildSql();

            $list = Db::table($comment_subquery . ' a')
                ->where($condition)
                ->order('id', 'desc')
                ->group('form_id')
                ->select();
            //print_r();die;
            foreach ($list as $k => $v) {
                $list[$k]['form_name'] = db('app_form')->where(['id' => $v['form_id']])->value('name');
            }
        } elseif ($status == 2) {
            //审核中 还没轮到我或者我审核完成了后面还有人没审核完成
            $condition['status'] = array('neq', 1);
            $condition['form_state'] = array('eq', 0);
            // $list=db('approval_process')->group('form_id')->where($condition)->select();
            $comment_subquery = Db::name('approval_process')
                ->order('id', 'desc')
                ->limit(100000)//不加有可能获取的不是最新的一条
                ->buildSql();

            $list = Db::table($comment_subquery . ' a')
                ->where($condition)
                ->order('id', 'desc')
                ->group('form_id')
                ->select();
            foreach ($list as $k => $v) {
                $list[$k]['form_name'] = db('app_form')->where(['id' => $v['form_id']])->value('name');
            }
        } elseif ($status == 3) {
            //审批完成
            $condition['form_state'] = array('eq', 1);
            // $list=db('approval_process')->group('form_id')->where($condition)->select();
            $comment_subquery = Db::name('approval_process')
                ->order('id', 'desc')
                ->limit(100000)//不加有可能获取的不是最新的一条
                ->buildSql();

            $list = Db::table($comment_subquery . ' a')
                ->where($condition)
                ->order('id', 'desc')
                ->group('form_id')
                ->select();
            foreach ($list as $k => $v) {
                $list[$k]['form_name'] = db('app_form')->where(['id' => $v['form_id']])->value('name');
            }
        } elseif ($status == 4) {
            //用章完成
            $condition['form_state'] = array('eq', 2);
            // $list=db('approval_process')->group('form_id')->where($condition)->select();
            $comment_subquery = Db::name('approval_process')
                ->order('id', 'desc')
                ->limit(100000)//不加有可能获取的不是最新的一条
                ->buildSql();

            $list = Db::table($comment_subquery . ' a')
                ->where($condition)
                ->order('id', 'desc')
                ->group('form_id')
                ->select();
            foreach ($list as $k => $v) {
                $list[$k]['form_name'] = db('app_form')->where(['id' => $v['form_id']])->value('name');
            }
        }
        $data['count1'] = $count1;
        $data['count2'] = $count2;
        $data['count3'] = $count3;
        $data['count4'] = $count4;
        $data['count5'] = $count5;
        if ($list) {
            foreach ($list as $k => $v) {
                $info = db('app_form')->where(['id' => $v['form_id']])->find();
                //文件编号
                $list[$k]['number'] = $info['number'];
                //印章名称
                $list[$k]['seal_name'] = db('seal')->where(['id' => $info['seal_id']])->value('name');
                //提交时间
                $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                //状态
                // if($info['status']==1){
                //     $list[$k]['status_name']='提交中';
                // }elseif($info['status']==2){
                //     $list[$k]['status_name']='审核中';
                // }elseif($info['status']==3){
                //     $list[$k]['status_name']='已拒绝';
                // }elseif($info['status']==4){
                //     $list[$k]['status_name']='审核完成';
                // }elseif($info['status']==5){
                //     $list[$k]['status_name']='用章完成';
                // }

                if ($v['status'] == 1) {
                    $list[$k]['status_name'] = '待审核';
                } elseif ($v['status'] == 2) {
                    //审核通过 ，看表单状态是否完成
                    $state = db('approval_process')->where(['id' => $v['id']])->value('form_state');
                    if ($state == 1) {
                        $list[$k]['status_name'] = '审核完成';
                    } else {
                        $list[$k]['status_name'] = '审核中';
                    }
                } elseif ($v['status'] == 3) {
                    //已拒绝
                    $list[$k]['status_name'] = '审核中';
                } elseif ($v['status'] == 4) {
                    //还没轮到我
                    $list[$k]['status_name'] = '审核中';
                }
                if ($v['form_state'] == 2) {
                    $list[$k]['status_name'] = '用章完成';
                }


            }
            $data['list'] = $list;
            return apireturn(1, '成功', $data);
        } else {
            $data['list'] = [];
            return apireturn(2, '暂无', $data);
        }

    }

    //我的审核页面，点击查看流程
    public function view_process123()
    {
        $form_id = $_POST['form_id'];
        if (!$form_id) {
            return apireturn(2, '表单ID为空');
        }
        $list = db('approval_process')->where(['form_id' => $form_id])->order('id desc')->select();
        foreach ($list as $k => $v) {
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $list[$k]['app_time'] = date('Y-m-d H:i:s', $v['app_time']);
            $list[$k]['username'] = db('user')->where(['id' => $v['uid']])->value('username');
            if ($v['status'] == 2) {
                $list[$k]['status_name'] = '通过';
            } elseif ($v['status'] == 3) {
                $list[$k]['status_name'] = '拒绝';
            } else {
                $list[$k]['status_name'] = '待审核';
            }
        }
        return apireturn(1, '成功', $list);
    }

    public function view_process()
    {
        $form_id = $_POST['form_id'];
        if (!$form_id) {
            return apireturn(2, '表单ID为空');
        }
        $list = db('approval_process')->group('number_of_submissions')->where(['form_id' => $form_id])->order('id desc')->select();
        foreach ($list as $k => $v) {
            $group_list[$k]['group'] = $v['number_of_submissions'];
            $bb = db('approval_process')->where(['form_id' => $form_id, 'number_of_submissions' => $v['number_of_submissions']])->order('id asc')->select();
            foreach ($bb as $kk => $vv) {
                $bb[$kk]['create_time'] = date('Y-m-d H:i:s', $vv['create_time']);
                if ($vv['app_time']) {
                    $bb[$kk]['app_time'] = date('Y-m-d H:i:s', $vv['app_time']);
                } else {
                    $bb[$kk]['app_time'] = '';
                }
                $bb[$kk]['username'] = db('user')->where(['id' => $vv['uid']])->value('username');
                if ($vv['status'] == 2) {
                    $bb[$kk]['status_name'] = '通过';
                } elseif ($vv['status'] == 3) {
                    $bb[$kk]['status_name'] = '拒绝';
                } else {
                    $bb[$kk]['status_name'] = '待审核';
                }
            }
            $group_list[$k]['list'] = $bb;
        }
        return apireturn(1, '成功', $group_list);
    }

    //删除表单
    public function del_form()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '对象ID为空');
        }
        $res = db('app_form')->where(['id' => $id])->delete();
        if ($res) {
            db('approval_process')->where(['form_id' => $id])->delete();
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    //申请单详情
    public function form_details()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '对象ID为空');
        }
        // $info=db('app_form')->where(['id'=>$id])->find();
        // if(!$info){
        //     return apireturn(2,'失败');
        // }
        $frequency = db('app_form')->where(['id' => $id])->value('frequency');
        if (!$frequency) {
            return apireturn(2, '失败');
        }
        // 删除印章同步记录
        $used_times = Db::name('use_log')->where(['app_id' => $id])->value('use_count');
        if ($used_times) {
            // $remaining_times=$info['frequency']-$used_times;
            $remaining_times = $frequency - $used_times;
            Db::name('app_form')->where(['id' => $id])->update(['used_times' => $used_times, 'remaining_times' => $remaining_times, 'chapter_time' => time()]);
            Db::name('use_log')->where(['app_id' => $id])->delete();
        }
        // $remaining_times=$info['frequency']-$used_times;
        // Db::name('app_form')->where(['id' => $id])->update(['used_times'=>$used_times,'remaining_times'=>$remaining_times,'chapter_time'=>time()]);
        // Db::name('use_log')->where(['app_id' => $id])->delete();
        $info = db('app_form')->where(['id' => $id])->find();
        //当前审核人
        $condition['form_id'] = $id;
        $condition['status'] = array('eq', 1);
        $reviewer = db('approval_process')->where($condition)->order('id desc')->value('uid');
        if ($reviewer) {
            $info['examine_uid'] = $reviewer;
            $info['reviewer'] = db('user')->where(['id' => $reviewer])->value('username');
        } else {
            $info['examine_uid'] = '';
            $info['reviewer'] = '';
        }
        if ($_POST['uid'] == $info['examine_uid']) {
            $info['uu'] = 1;
        } else {
            $info['uu'] = '';
        }
        $info['applicant'] = db('user')->where(['id' => $info['uid']])->value('username');
        $info['create_time'] = date('Y-m-d H:i:s', $info['create_time']);
        if ($info['status'] == 1) {
            $info['status_name'] = '提交中';
        } elseif ($info['status'] == 2) {
            $info['status_name'] = '审核中';
        } elseif ($info['status'] == 3) {
            $info['status_name'] = '已拒绝';
            $ll = db('approval_process')->where(['form_id' => $id])->order('id asc')->select();
            //print_r($ll);die;
            foreach ($ll as $k => $v) {
                if ($v['remark']) {
                    if ($v['remark'] == 1) {
                        $reason = '文件名称不全，请核实';
                    } elseif ($v['remark'] == 2) {
                        $reason = '用章次数可能过多，请重新设置';
                    } elseif ($v['remark'] == 3) {
                        $reason = '图片上传不够清晰，请核对后重新上传';
                    } elseif ($v['remark'] == 4) {
                        $reason = $v['remark_content'];
                        //$reason='';
                    } else {
                        $reason = $v['remark_content'];
                    }
                }
            }

            $info['reason'] = $reason;
        } elseif ($info['status'] == 4) {
            $info['status_name'] = '审核通过';
        } elseif ($info['status'] == 5) {
            $info['status_name'] = '用章完成';
        } elseif ($info['status'] == 6) {
            $info['status_name'] = '用章完成';
        }
        //印章名称
        $info['seal_name'] = db('seal')->where(['id' => $info['seal_id']])->value('name');

        //审批类型
        $info['app_typename'] = db('approval')->where(['id' => $info['app_id']])->value('type_name');
        if ($info['imgs']) {
            $imgs = explode(',', $info['imgs']);
            foreach ($imgs as $k => $v) {
                //$imgs[$k]="http://" . $_SERVER['HTTP_HOST'] .db('picture')->where(['id'=>$v])->value('path');
                $imgss[$k] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $v])->value('path');
                $pd[$k] = $v;
            }
            $info['imgss'] = $imgss;
            $info['pd'] = $pd;
        }
        //文档
        if ($info['file']) {
            $file = explode(',', $info['file']);
            foreach ($file as $k => $v) {
                $bb[$k]['src'] = "https://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $v])->value('path');
                $bb[$k]['name'] = db('picture')->where(['id' => $v])->value('name');
            }
            $info['wd'] = $bb;
        } else {
            $info['wd'] = '';
        }
        //上传文档
        if ($info['used_file']) {
            $used_file = explode(',', $info['used_file']);
            foreach ($used_file as $k => $v) {
                $cc[$k]['src'] = "https://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $v])->value('path');
                $cc[$k]['name'] = db('picture')->where(['id' => $v])->value('name');
            }
            $info['used_wd'] = $cc;
        } else {
            $info['used_wd'] = '';
        }

        if ($info['used_img']) {
            $imgss = explode(',', $info['used_img']);
            foreach ($imgss as $k => $v) {
                $imgss[$k] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $v])->value('path');
            }
            $info['used_img'] = $imgss;
        }
        if ($info['chapter_time']) {
            $info['chapter_time'] = date('Y-m-d H:i:s', $info['chapter_time']);
        } else {
            $info['chapter_time'] = '';
        }
        // $len=mb_strlen($info['name'],'utf-8');
        // if($len>14){
        //     $info['str_name']=mb_substr($info['name'],0,14,'utf-8').'...';
        // }else{
        //     $info['str_name']=$info['name'];
        // }
        $info['str_name'] = $info['name'];
        if ($info['used_times'] > $info['frequency']) {
            $info['used_times'] = $info['frequency'];
        }
        if ($info['remaining_times'] < 0) {
            $info['remaining_times'] = 0;
        }

        return apireturn(1, '成功', $info);
    }
    //申请详情（用章详情）跟上面的申请单详情比起来就是多了上传的图片字段(先不写接口，到时应该跟上面可以共用一个接口)

    //我的审核 点击同意或者拒绝
    public function to_examine123()
    {
        //申请表单ID
        $form_id = $_POST['form_id'];
        if (!$form_id) {
            return apireturn(2, '表单ID为空');
        }
        //审批人ID
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '审批人ID为空');
        }
        //state 1:同意 2：拒绝
        $state = $_POST['state'];
        if (!$state) {
            return apireturn(2, '操作类型为空');
        }
        if ($state == 1) {
            //同意 同意的话还要看后面的有没有人，审批流程有没有结束
            db('approval_process')->where(['form_id' => $form_id, 'uid' => $uid])->update(['status' => 1]);
            $id = db('approval_process')->where(['form_id' => $form_id, 'uid' => $uid])->value('id');
            $id_list = db('approval_process')->where(['form_id' => $form_id])->field('id')->select();

            $max_ids = max($id_list);
            $max_id = $max_ids['id'];
            // print_r($id);die;
            //看最大值大于$id不，大于就代表后面还有审批人
            if ($max_id > $id) {
                $next_id = $id + 1;
                //轮到下一个人审核 status:0为当前审核人
                db('approval_process')->where(['id' => $next_id])->update(['status' => 0]);
            } else {
                //审批流程走完了
                db('approval_process')->where(['form_id' => $form_id])->update(['form_state' => 1]);
                db('app_form')->where(['id' => $form_id])->update(['status' => 4]);
            }
        } elseif ($state == 2) {
            //要写拒绝原因
            $remark = $_POST['remark'];
            if (!$remark) {
                return apireturn(2, '拒绝原因不能为空');
            }
            db('app_form')->where(['id' => $form_id])->update(['status' => 3]);
            db('approval_process')->where(['form_id' => $form_id, 'uid' => $uid])->update(['status' => 2, 'remark' => $remark]);
        }
        return apireturn(1, '成功');
    }


    public function to_examine()
    {
        //申请表单ID
        $form_id = $_POST['form_id'];
        if (!$form_id) {
            return apireturn(2, '表单ID为空');
        }
        //审批人ID
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '审批人ID为空');
        }
        //state 1:同意 2：拒绝
        $state = $_POST['state'];
        if (!$state) {
            return apireturn(2, '操作类型为空');
        }
        //可能提交了几次，找到最大的那条记录ID
        $mid = db('approval_process')->where(['form_id' => $form_id, 'uid' => $uid])->order('id desc')->value('id');
        //file_put_contents('330.txt',print_r($mid,true));
        if ($state == 1) {
            //同意 同意的话还要看后面的有没有人，审批流程有没有结束

            //print_r($mid);die;
            db('approval_process')->where(['id' => $mid])->update(['status' => 2, 'app_time' => time()]);

            $id_list = db('approval_process')->where(['form_id' => $form_id])->order('id asc')->field('id')->select();
            //file_put_contents('338888.txt',print_r($id_list,true));
            $max_ids = max($id_list);
            $max_id = $max_ids['id'];
            $ids = array_column($id_list, 'id');
            //当前ID的下标值
            $key = array_search($mid, $ids);
            //file_put_contents('339999.txt',print_r($key,true));
            //看最大值大于$id不，大于就代表后面还有审批人
            if ($max_id > $mid) {
                // $next_id=$mid+1;
                //file_put_contents('33011.txt',print_r($max_id,true));
                $next_id = $id_list[$key + 1]['id'];
                //file_put_contents('33022.txt',print_r($next_id,true));
                //轮到下一个人审核 status:1为当前审核人
                db('approval_process')->where(['id' => $next_id])->update(['status' => 1]);


                //openid:审核人的app_openid   $uid 申请人的uid  $res  表单ID
                $sh_uid = db('approval_process')->where(['id' => $next_id])->value('uid');
                $openid = db('user')->where(['id' => $sh_uid])->value('app_openid');

                $form_id = db('approval_process')->where(['id' => $next_id])->value('form_id');
                $sq_uid = db('app_form')->where(['id' => $form_id])->value('uid');
                /**
                 * TODO：发送模板消息（用章申请提醒）
                 * */
                $this->send_subscribe($openid, $sq_uid, $form_id);
            } else {
                //审批流程走完了
                db('approval_process')->where(['form_id' => $form_id])->update(['form_state' => 1]);
                db('app_form')->where(['id' => $form_id])->update(['status' => 4]);
                //走完了，要发送通知给申请人
                //openid:申请人的app_openid   $uid 申请人的uid  $res  表单ID
                $uid = db('app_form')->where(['id' => $form_id])->value('uid');
                $openid = db('user')->where(['id' => $uid])->value('app_openid');
                /**
                 * TODO：发送模板消息（用章申请完成提醒）
                 * */
                $this->send_subscribe31($openid, $uid, $form_id);
            }
        } elseif ($state == 2) {
            //要写拒绝原因
            $remark = $_POST['remark'];
            $remark_content = $_POST['remark_content'];
            if (!$remark_content) {
                $remark_content = '';
            } else {
                $remark = 4;
            }
            // if(!$remark){
            //     return apireturn(2,'拒绝原因不能为空');
            // }
            db('app_form')->where(['id' => $form_id])->update(['status' => 3]);
            db('approval_process')->where(['id' => $mid])->update(['status' => 3, 'remark' => $remark, 'remark_content' => $remark_content, 'app_time' => time()]);
        }
        return apireturn(1, '成功');
    }

    //已拒绝页面，再次提交申请
    public function reapply()
    {
        $form_id = $_POST['form_id'];
        if (!$form_id) {
            return apireturn(2, '表单ID为空');
        }
        $company_id = $_POST['company_id'];
        $data['name'] = $_POST['name'];
        $data['number'] = $_POST['number'];
        $data['frequency'] = $_POST['frequency'];
        $data['remaining_times'] = $_POST['frequency'];
        $data['imgs'] = $_POST['imgs'];
        $data['dd_file'] = $_POST['dd_file'];
        $data['remark'] = $_POST['remark'];
        $data['status'] = 1;
        $res = db('app_form')->where(['id' => $form_id])->update($data);
        if ($res) {
            //提交成功我就添加审核流程
            //这次是几次提交
            $submissions = db('approval_process')->where(['form_id' => $form_id])->order('id desc')->field('number_of_submissions')->find();
            $submissions_id = $submissions['number_of_submissions'] + 1;
            //审批类型ID
            $app_id = $_POST['app_id'];
            //审批流程

            $is_free = db('approval')->where(['id' => $app_id])->value('is_free');
            if ($is_free == 2) {
                //自由审批流程
                $info = db('approval_process')->where(['form_id' => $form_id])->find();

                $add_data['uid'] = $info['uid'];
                $add_data['form_id'] = $form_id;
                $add_data['create_time'] = time();
                $add_data['company_id'] = $company_id;
                $add_data['number_of_submissions'] = $submissions_id;

                $add_data['status'] = 1;
                db('approval_process')->insert($add_data);

            } else {
                $app_list = db('approver')->where(['app_id' => $app_id])->order('sort asc')->select();
                foreach ($app_list as $k => $v) {
                    $add_data['uid'] = $v['uid'];
                    $add_data['form_id'] = $form_id;
                    $add_data['create_time'] = time();
                    $add_data['company_id'] = $company_id;
                    $add_data['number_of_submissions'] = $submissions_id;

                    if ($k == 0) {
                        //轮到他审批，第一个人是当前审批人
                        $add_data['status'] = 1;
                    } else {
                        $add_data['status'] = 4;
                    }
                    db('approval_process')->insert($add_data);
                }
            }


            return apireturn(1, '成功', $res);
        } else {
            return apireturn(2, '失败');
        }

    }

    //删除审批类型
    public function del_sp()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '对象ID为空');
        }
        $res = db('approval')->where(['id' => $id])->update(['is_del' => 1]);
        if ($res) {
            db('approver')->where(['app_id' => $id])->delete();
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    public function is_state123()
    {
        $uid = $_POST['uid'];
        if (!is_numeric($uid)) {
            return apireturn(2, '用户ID为空');
        }
        $company_id = $_POST['company_id'];
        if (!is_numeric($company_id)) {
            return apireturn(2, '公司ID为空');
        }
        $status = db('staff')->where(['uid' => $uid, 'company_id' => $company_id])->value('status');
        if ($status == 1 || $status == 2) {
            return apireturn(1, '成功', $status);
        } elseif ($status == 3) {
            return apireturn(2, '用户已禁用');
        } else {
            return apireturn(2, '失败');
        }
    }

    public function is_state()
    {
        $uid = $_POST['uid'];
        if (!is_numeric($uid)) {
            return apireturn(2, '用户ID为空');
        }
        $company_id = $_POST['company_id'];
        if (!is_numeric($company_id)) {
            return apireturn(2, '公司ID为空');
        }
        $data['status'] = db('staff')->where(['uid' => $uid, 'company_id' => $company_id])->value('status');
        $data['up_count'] = 200;
        if ($data['status'] == 1 || $data['status'] == 2) {
            return apireturn(1, '成功', $data);
        } elseif ($data['status'] == 3) {
            return apireturn(2, '用户已禁用');
        } else {
            return apireturn(2, '失败');
        }
    }

    //删除部门
    public function del_partment()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '对象ID为空');
        }
        $res = db('department')->where(['id' => $id])->update(['is_del' => 1]);
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    //印章管理
    public function seal_manage()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }

        $configModel = new \app\admin\model\Config();
        $res = $configModel->getConfigCacheByName(Constants::$SEAL_TYPE_KEY);
        $type_list = array_merge($res);

        //搜索
        $where['company_id'] = $company_id;
        $_POST['name'] ? $where['name'] = array('like', "%$_POST[name]%") : '';
        $where['is_del'] = array('eq', 0);
        $seal_list = db('seal')->where($where)->select();
        foreach ($seal_list as $k => $v) {
            if ($v['img']) {
                $seal_list[$k]['img'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $v['img']])->value('path');
            } else {
                $seal_list[$k]['img'] = '';
            }
            if ($v['status'] == 2) {
                $seal_list[$k]['status_name'] = '可用';
            } elseif ($v['status'] == 3) {
                $seal_list[$k]['status_name'] = '损坏';
            } elseif ($v['status'] == 4) {
                $seal_list[$k]['status_name'] = '维修';
            } else {
                $seal_list[$k]['status_name'] = '禁用';
            }
            $seal_list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);

            $ids = array_column($type_list, 'id');
            //当前ID的下标值
            $key = array_search($v['seal_type'], $ids);
            $seal_list[$k]['type_name'] = $type_list[$key]['name'];
        }
        if ($seal_list) {
            return apireturn(1, '成功', $seal_list);
        } else {
            return apireturn(2, '暂无数据', []);
        }
    }

    //印章详情
    public function seal_detail()
    {
        $id = $_POST['seal_id'];
        if (!$id) {
            return apireturn(2, '对象ID为空');
        }

        $configModel = new \app\admin\model\Config();
        $res = $configModel->getConfigCacheByName(Constants::$SEAL_TYPE_KEY);
        $type_list = array_merge($res);
        // $ids = array_column($type_list,'id');
        // //当前ID的下标值
        // $key = array_search($v['seal_type'], $ids);
        // $seal_list[$k]['type_name']=$type_list[$key]['name'];


        $info = db('seal')->where(['id' => $id])->find();
        //$info['img']="http://" . $_SERVER['HTTP_HOST'] .db('picture')->where(['id'=>$info['img']])->value('path');
        if ($info['img']) {
            $info['img'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $info['img']])->value('path');
        } else {
            $info['img'] = '../../images/img_scyz.jpg';
        }
        $info['type_id'] = $info['seal_type'] - 1;
        $info['status'] = $info['status'] - 1;

        if ($info['department']) {
            $department = explode(',', $info['department']);
            foreach ($department as $k => $v) {

                $name .= '/' . db('department')->where(['id' => $v])->value('name');

            }
            $info['department_name'] = substr($name, 1);
        }
        $info['date_received'] = date('Y-m-d', $info['date_received']);
        $data['info'] = $info;
        $uu_list = $department;
        $condition['company_id'] = $info['company_id'];
        $condition['is_del'] = array('eq', 0);
        $list = db('department')->where($condition)->select();
        foreach ($list as $k => $v) {
            if (in_array($v['id'], $uu_list)) {
                $list[$k]['is_ck'] = 1;
            } else {
                $list[$k]['is_ck'] = 2;
            }
        }
        $data['list'] = $list;
        $data['type_list'] = $type_list;
        return apireturn(1, '成功', $data);
    }

    //新增印章回显
    public function add_seal_echo()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID不能为空');
        }
        $list = db('department')->where(['company_id' => $company_id, 'is_del' => 0])->select();
        $data['list'] = $list;


        $configModel = new \app\admin\model\Config();
        $res = $configModel->getConfigCacheByName(Constants::$SEAL_TYPE_KEY);
        $type_list = array_merge($res);
        $data['type'] = $type_list;
        return apireturn(1, '成功', $data);
    }

    public function add_seal_echo726()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID不能为空');
        }
        $list = db('department')->where(['company_id' => $company_id, 'is_del' => 0])->select();
        $data['list'] = $list;


        $configModel = new \app\admin\model\Config();
        $res = $configModel->getConfigCacheByName(Constants::$SEAL_TYPE_KEY);
        $type_list = array_merge($res);
        $data['type'] = $type_list;
        //查找已有印章的number集合
        $number_list = db('seal')->where(['is_del' => 0])->group('number')->field('number')->select();
        //print_r($number_list);die;
        if ($number_list) {
            foreach ($number_list as $k => $v) {
                $number1 .= ',' . $v['number'];
            }
            $data['number'] = substr($number1, 1);
        } else {
            $data['number'] = '';
        }
        return apireturn(1, '成功', $data);
    }

    //选择蓝牙之后，判断设备编号是否已录入
    public function choice()
    {
        $equipment_number = $_POST['equipment_number'];
        if (!$equipment_number) {
            return apireturn(2, '设备编号不能为空');
        }
        $res = db('device')->where(['device_code' => $equipment_number])->find();
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    //选择部门
    public function choose_partment()
    {
        $partment_id = $_POST['de_id'];
        file_put_contents('369.txt', print_r($partment_id, true));
        $partment_list = explode(',', $partment_id);
        foreach ($partment_list as $k => $v) {

            $name .= '/' . db('department')->where(['id' => $v])->value('name');

        }
        $name = substr($name, 1);
        return apireturn(1, '成功', $name);
    }

    //新增印章 编辑
    public function add_seal()
    {
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID为空');
        }
        $name = $_POST['name'];
        if (!$name) {
            return apireturn(2, '印章名称为空');
        }
        $add_data['name'] = $name;
        //设备编号是蓝牙搜索出来机器的编号
        $number = $_POST['number'];
        if (!$number) {
            return apireturn(2, '设备编号为空');
        }
        $add_data['number'] = $number;

        $re = db('device')->where(['device_code' => $number])->find();
        if (!$re) {
            return apireturn(2, '设备编号错误');
        }
        $value = db('seal')->where(['number' => $number, 'company_id' => $_POST['company_id'], 'is_del' => 0])->find();
        if ($value) {
            return apireturn(2, '相同的印章不能重复添加');
        }
        //印章类型 印章类型是总后台配置的
        $seal_type = $_POST['seal_type'];
        // if(!$seal_type){
        //     return apireturn(2,'印章类型为空');
        // }
        $add_data['seal_type'] = $seal_type;
        // $add_data['date_received']=$_POST['date_received'];
        //所属部门 可以多个部门
        $department_id = $_POST['department_id'];
        if (!$department_id) {
            return apireturn(2, '部门不能为空');
        }
        $add_data['department'] = $department_id;
        $add_data['company_id'] = $_POST['company_id'];
        $img = $_POST['img'];
        //if(!$img){
        //    return apireturn(2,'印章样式为空');
        //}
        $add_data['img'] = $img;
        $add_data['remark'] = $_POST['remark'];

        $id = $_POST['id'];
        if ($id) {
            //编辑
            $add_data['updater'] = $uid;
            $add_data['update_time'] = time();
            $res = db('seal')->where(['id' => $id])->update($add_data);
        } else {
            //新增
            $add_data['date_received'] = time();
            $add_data['creator'] = $uid;
            $add_data['maintenance_due'] = strtotime("+1year");
            $add_data['expired_time'] = strtotime("+1year");
            $add_data['create_time'] = time();
            $res = db('seal')->insertGetId($add_data);
        }
        return apireturn(1, '成功');
    }

    //保存
    public function save_seal()
    {
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID为空');
        }
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '对象ID为空');
        }
        $add_data = $_POST;
        if (!$_POST['img']) {
            unset($add_data['img']);
        }
        unset($add_data['uid']);
        //编辑
        $add_data['updater'] = $uid;
        $add_data['update_time'] = time();
        $res = db('seal')->where(['id' => $id])->update($add_data);

        return apireturn(1, '成功');
    }

    //审批类型列表
    public function app_list()
    {
        $seal_id = $_POST['seal_id'];
        if (!$seal_id) {
            return apireturn(2, '印章ID为空');
        }
        $condition['seal_id'] = $seal_id;
        //搜索的话type_name有值
        $_POST['type_name'] ? $condition['type_name'] = array('like', "%$_POST[type_name]%") : '';
        // print_r($condition);die;
        $condition['is_del'] = 0;
        $list = db('approval')->where($condition)->order('sort asc,id desc')->select();
        foreach ($list as $k => $v) {
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            if ($v['status'] == 1) {
                $list[$k]['status_name'] = '启用';
            } else {
                $list[$k]['status_name'] = '禁用';
            }
            if ($v['is_free'] == 1) {
                $list[$k]['free_name'] = '否';
            } else {
                $list[$k]['free_name'] = '是';
            }
        }
        if ($list) {
            return apireturn(1, '成功', $list);
        } else {
            return apireturn(2, '暂无数据', []);
        }
    }

    //新增审批类型
    public function app_type()
    {
        $add_data['seal_id'] = $_POST['seal_id'];
        if (!$_POST['seal_id']) {
            return apireturn(2, '印章ID为空');
        }
        $add_data['sort'] = $_POST['sort'];
        if (!$_POST['sort']) {
            return apireturn(2, '序号为空');
        }
        $add_data['type_name'] = $_POST['type_name'];
        if (!$_POST['type_name']) {
            return apireturn(2, '审批类型名称为空');
        }
        $add_data['file_remark'] = $_POST['file_remark'];

        $add_data['status'] = $_POST['status'];
        $add_data['is_free'] = $_POST['is_free'];
        $add_data['create_time'] = time();
        $res = db('approval')->insertGetId($add_data);
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    //审批类型设置审批流程(流程设置页面)
    public function manage_process()
    {
        //审批类型ID
        $app_id = $_POST['app_id'];
        if (!$_POST['app_id']) {
            return apireturn(2, '审批类型ID为空');
        }
        $list = db('approver')->where(['app_id' => $app_id])->order('sort asc')->select();
        foreach ($list as $k => $v) {
            //显示一个部门就行了，如果后面要显示多个部门再调整
            $seal_id = db('approval')->where(['id' => $app_id])->value('seal_id');
            $company_id = db('seal')->where(['id' => $seal_id])->value('company_id');

            // db('approval')->alias('a')->join('seal b','a.seal_id=b.id','LEFT')->where(['a.id'=>$app_id])->value('b.company_id');

            $department_id = db('staff')->where(['uid' => $v['uid'], 'company_id' => $company_id])->field('department_id')->find();
            $list[$k]['department_name'] = db('department')->where(['id' => $department_id['department_id']])->value('name');
            $list[$k]['username'] = db('user')->where(['id' => $v['uid']])->value('username');
        }
        if ($list) {
            return apireturn(1, '成功', $list);
        } else {
            return apireturn(2, '暂无数据', []);
        }
    }

    //操作上移下移
    public function move()
    {
        $app_id = $_POST['app_id'];
        if (!$app_id) {
            return apireturn(2, '审批类型ID为空');
        }
        //这个UID是指被移动的那个审批人uid
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '移动对象为空');
        }
        //move 1:上移 2：下移
        $move = $_POST['move'];
        if (!$move) {
            return apireturn(2, '操作类型为空');
        }
        if ($move == 1) {
            $sort = db('approver')->where(['app_id' => $app_id, 'uid' => $uid])->value('sort');
            if ($sort == 1) {
                return apireturn(2, '已经是第一行，不能上移了');
            } else {
                $bsort = $sort - 1;
                $id = db('approver')->where(['app_id' => $app_id, 'sort' => $bsort])->value('id');
                //前面那位sort加一，他减一就相当于换位了
                db('approver')->where(['id' => $id])->setInc('sort', 1);
                db('approver')->where(['app_id' => $app_id, 'uid' => $uid])->setDec('sort', 1);
            }
        } elseif ($move == 2) {
            $sort = db('approver')->where(['app_id' => $app_id, 'uid' => $uid])->value('sort');
            $count = db('approver')->where(['app_id' => $app_id])->count();
            // print_r($count);die;
            if ($sort >= $count) {
                return apireturn(2, '已经是最后一行，不能下移了');
            } else {
                $bsort = $sort + 1;
                $id = db('approver')->where(['app_id' => $app_id, 'sort' => $bsort])->value('id');
                db('approver')->where(['id' => $id])->setDec('sort', 1);
                //自己加一，后面的人减一
                db('approver')->where(['app_id' => $app_id, 'uid' => $uid])->setInc('sort', 1);
            }
        }
        return apireturn(1, '成功');
    }

    //删除审批人
    public function del_approver()
    {
        $app_id = $_POST['app_id'];
        if (!$app_id) {
            return apireturn(2, '审批类型为空');
        }
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '操作对象为空');
        }
        $res = db('approver')->where(['id' => $id])->delete();
        $list = db('approver')->where(['app_id' => $app_id])->order('sort asc')->select();
        foreach ($list as $k => $v) {
            $list[$k]['sort'] = $k + 1;
        }
        return apireturn(1, '成功', $res);
    }

    //选择审批人之审批人列表
    public function select_approver()
    {
        // $seal_id=$_POST['seal_id'];
        // if(!$seal_id){
        //     return apireturn(2,'印章ID为空');
        // }
        //公司ID
        // $company_id=db('seal')->where(['id'=>$seal_id])->value('company_id');
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apiReturn(2, '公司ID为空');
        }

        $app_id = $_POST['app_id'];

        $condition['a.company_id'] = $company_id;
        //$_POST['username']?$condition['b.username']=$_POST['username']:'';
        if ($_POST['username']) {
            //$where['custom_name|custom_phone']
            $condition['b.username|b.account'] = array('like', "%$_POST[username]%");
        }

        $u_list = db('approver')->where(['app_id' => $app_id])->field('uid')->select();
        foreach ($u_list as $k => $v) {
            if ($k == 0) {
                $uu = $v['uid'];
            } else {
                $uu .= ',' . $v['uid'];
            }
        }
        $uu_list = explode(',', $uu);
        //$list=db('staff')->alias('a')->join('user b','a.uid=b.id','LEFT')->group('uid')->where($condition)->field('a.*')->select();
        $condition['c.is_approver'] = 2;//是审批人才可以
        $list = db('staff')->alias('a')->join('user b', 'a.uid=b.id', 'LEFT')->join('position c', 'a.position_id=c.id', 'LEFT')->group('uid')->where($condition)->field('a.*')->select();
        //print_r($list);die;
        foreach ($list as $k => $v) {
            $dd = db('user')->where(['id' => $v['uid']])->find();
            if ($dd) {
                // print_r($v['uid']);die;
                $list[$k]['name'] = db('user')->where(['id' => $v['uid']])->value('username');
                $list[$k]['mobile'] = db('user')->where(['id' => $v['uid']])->value('mobile');
                if (in_array($v['uid'], $uu_list)) {
                    // $list[$k]['is_cz']=1;
                    unset($list[$k]);
                } else {
                    if ($v['department_id']) {
                        $a = explode(',', $v['department_id']);
                        foreach ($a as $kk => $vv) {
                            if ($kk == 0) {
                                $partment = db('department')->where(['id' => $vv])->value('name');
                            } else {
                                $partment .= ',' . db('department')->where(['id' => $vv])->value('name');
                            }

                        }

                    }
                    $list[$k]['department_list'] = $partment;
                }
            } else {
                unset($list[$k]);
            }


        }
        $list1 = array_merge($list);
        if ($list) {
            return apireturn(1, '成功', $list1);
        } else {
            return apireturn(2, '暂无数据', []);
        }
    }

    //选择审批人之后  弃用  是单选框 不是一次选几个
    public function choose_approver1229()
    {
        $app_id = $_POST['app_id'];
        if (!$app_id) {
            return apireturn(2, '审批类型ID为空');
        }
        //选择的审批人ID集合 以逗号隔开的
        $ids = $_POST['ids'];
        if (!$ids) {
            return apireturn(2, '审批人为空');
        }
        $id_list = explode(',', $ids);

        //审核类型审批人表
        $count = db('approver')->where(['app_id' => $app_id])->count();

        foreach ($id_list as $k => $v) {
            $count++;
            $add_data['uid'] = $v;
            $add_data['create_time'] = time();
            $add_data['app_id'] = $app_id;
            $add_data['sort'] = $count;
            $res = db('approver')->insertGetId($add_data);
        }
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    public function choose_approver()
    {
        $app_id = $_POST['app_id'];
        if (!$app_id) {
            return apireturn(2, '审批类型ID为空');
        }
        $uid = $_POST['uid'];
        if ($uid == 'undefined') {
            return apireturn(2, '请选择审批人');
        }
        //审核类型审批人表
        $count = db('approver')->where(['app_id' => $app_id])->count();

        $count++;
        $add_data['uid'] = $uid;
        $add_data['create_time'] = time();
        $add_data['app_id'] = $app_id;
        $add_data['sort'] = $count;
        $res = db('approver')->insertGetId($add_data);

        if ($res) {
            return apireturn(1, '成功', $app_id);
        } else {
            return apireturn(2, '失败');
        }
    }

    //部门管理
    public function department_management()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }

        //一级部门列表
        $sub_list = db('department')->where(['pid' => 0, 'company_id' => $company_id, 'is_del' => 0])->order('id desc')->select();

        //可能查上级部门
        // if($_POST['pid']){


        if (is_numeric($_POST['pid']) === false) {

        } else {
            // print_r($_POST['pid']);die;
            //现在PID是下标，小程序是传的下标过来的
            // $_POST['pid']?$where['pid']=$_POST['pid']:'';
            $sub_id = $_POST['pid'];
            $where['id'] = $sub_list[$sub_id]['id'];
        }

        // }else{
        $_POST['name'] ? $where['name'] = array('like', "%$_POST[name]%") : '';
        // }
        $where['company_id'] = $company_id;
        $where['is_del'] = array('eq', 0);
        $list = db('department')->where($where)->select();
        foreach ($list as $k => $v) {
            if ($v['pid'] == 0) {
                //无上级部门
                $list[$k]['superior_name'] = '无';
            } else {
                //上级部门名称
                $list[$k]['superior_name'] = db('department')->where(['id' => $v['pid']])->value('name');
            }
            if ($v['sort'] == 0) {
                $list[$k]['sort'] = 9999;
            }
        }

        foreach ($list as $key => $row) {
            $volume[$key] = $row['sort'];
            $edition[$key] = $row['create_time'];
        }

        array_multisort($volume, SORT_ASC, $edition, SORT_DESC, $list);
        $sub_list ? $data['sub_list'] = $sub_list : [];
        $list ? $data['list'] = $list : [];
        return apireturn(1, '成功', $data);
    }

    public function del_position()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '对象ID为空');
        }
        $res = db('position')->where(['id' => $id])->delete();
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    public function del_user()
    {
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '对象ID为空');
        }
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }
        $res = db('staff')->where(['uid' => $uid, 'company_id' => $company_id])->delete();
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    //新增部门回显
    public function department_echo()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }

        //一级部门列表
        $sub_list = db('department')->where(['pid' => 0, 'company_id' => $company_id, 'is_del' => 0])->order('id desc')->select();
        $id = $_POST['id'];
        if ($id) {
            //编辑页面
            $info = db('department')->where(['id' => $id])->find();

            if ($info['pid']) {
                // $info['p_name']=db('department')->where(['id'=>$info['pid']])->value('name');
                $ids = array_column($sub_list, 'id');
                //当前ID的下标值
                $key = array_search($info['pid'], $ids);
                $info['xb'] = $key;
            }
        } else {
            $info['xb'] = '';
        }
        $data['sub_list'] = $sub_list;
        $data['info'] = $info;
        return apireturn(1, '成功', $data);
    }

    //新增部门回显
    public function department_echo81()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }

        //一级部门列表
        $sub_list = db('department')->where(['pid' => 0, 'company_id' => $company_id, 'is_del' => 0])->order('id desc')->field('id,name')->select();
        $id = $_POST['id'];
        if ($id) {
            //编辑页面
            $info = db('department')->where(['id' => $id])->find();
            if ($info['pid']) {
                $ids = array_column($sub_list, 'id');
                //当前ID的下标值
                $key = array_search($info['pid'], $ids);
                $info['xb'] = $key;
            }
        } else {
            $info['xb'] = '';
        }
        $list = array(array('id' => 0, 'name' => '暂无'));
        $data['sub_list'] = array_merge($list, $sub_list);
        // $data['sub_list']=$sub_list;

        $data['info'] = $info;
        return apireturn(1, '成功', $data);
    }

    //新增部门
    public function add_department()
    {
        file_put_contents('999.txt', print_r($_POST, true));
        $add_data['company_id'] = $_POST['company_id'];
        if ($_POST['name'] == 'undefined') {
            return apireturn(2, '名称不能为空');
        }
        $company_id = $_POST['company_id'];
        if (!$_POST['company_id']) {
            return apireturn(2, '公司ID为空');
        }
        $add_data['name'] = $_POST['name'];
        if (!$_POST['name']) {
            return apireturn(2, '部门名称为空');
        }
        // $_POST['pid']?$add_data['pid']=$_POST['pid']:'';
        $add_data['describe'] = $_POST['describe'];

        //pid是下标
        $sub_id = $_POST['pid'];
        if (is_numeric($sub_id) === false) {

        } else {
            $sub_list = db('department')->where(['pid' => 0, 'company_id' => $company_id, 'is_del' => 0])->order('id desc')->select();
            // file_put_contents('999.txt',print_r($sub_list,true));die;
            $add_data['pid'] = $sub_list[$sub_id]['id'];
        }

        $add_data['sort'] = $_POST['sort'];

        if (is_numeric($_POST['id'])) {
            //传了ID就是编辑
            $res = db('department')->where(['id' => $_POST['id']])->update($add_data);
        } else {


            $add_data['create_time'] = time();
            $res = db('department')->insertGetId($add_data);
        }

        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    //职位列表
    public function position_index()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }
        $where['company_id'] = $company_id;
        $_POST['name'] ? $where['name'] = array('like', "%$_POST[name]%") : '';
        $list = db('position')->where($where)->select();
        foreach ($list as $k => $v) {
            $list[$k]['create_time'] = date('Y-m-d', $v['create_time']);
        }
        if ($list) {
            return apireturn(1, '成功', $list);
        } else {
            return apireturn(2, '暂无数据', []);
        }
    }

    //职位管理
    public function add_position()
    {
        $add_data['company_id'] = $_POST['company_id'];
        if (!$_POST['company_id']) {
            return apireturn(2, '公司ID为空');
        }
        $add_data['name'] = $_POST['name'];
        if (!$_POST['name']) {
            return apireturn(2, '职位名称为空');
        }
        $add_data['describe'] = $_POST['describe'];
        $add_data['is_approver'] = $_POST['is_approver'];
        if ($_POST['id']) {
            $res = db('position')->where(['id' => $_POST['id']])->update($add_data);
        } else {
            $add_data['create_time'] = time();
            $res = db('position')->insertGetId($add_data);
        }
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }

    }

    public function position_echo()
    {
        $id = $_POST['id'];
        if ($id) {
            $info = db('position')->where(['id' => $id])->find();
            if ($info['is_approver'] == 1) {
                $info['index'] = 0;
            } else {
                $info['index'] = 1;
            }
        } else {
            $info = '';
            $info['index'] = '';
        }
        return apireturn(1, '成功', $info);
    }

    //用户管理
    public function user_manage()
    {
        // $uid=$_POST['uid'];
        // if(!$uid){
        //     return apireturn(2,'用户ID为空');
        // }
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }
        $where['a.company_id'] = $_POST['company_id'];
        //$_POST['name']?$where['b.username']=array('like',"%$_POST[name]%"):'';
        //$_POST['name']?$where['b.account']=array('like',"%$_POST[name]%"):'';
        if ($_POST['name']) {
            $where['b.username|b.account'] = array('like', "%$_POST[name]%");
        }


        // db('staff')->where($where)->select();
        $list = db('staff')->alias('a')->join('user b', 'a.uid=b.id', 'LEFT')->group('uid')->where($where)->order('a.id desc')->field('b.id,b.username,b.mobile,a.department_id')->select();
        //print_r($list);die;
        foreach ($list as $k => $v) {
            if (!$v['id']) {
                unset($list[$k]);
            }
        }
        $list1 = array_merge($list);

        if ($_POST['department_id']) {
            $department_id = $_POST['department_id'];
            //$where['a.department_id'] = ['exp',"FIND_IN_SET($department_id,department_id)"];
            //print_r($list1);die;
            foreach ($list1 as $k => $v) {
                $li = explode(',', $department_id);
                $id_list = explode(',', $v['department_id']);

                //判断两个数组之间有没有相同的值
                $res = array_intersect($li, $id_list);
                if (!$res) {
                    unset($list1[$k]);
                }

            }


        }

        $list2 = array_merge($list1);
        $sub_list = db('department')->where(['company_id' => $company_id, 'is_del' => 0])->order('id desc')->select();
        //print_r($sub_list);
        $sub = array(array('id' => 1, 'name' => '外编部门', 'pid' => 0, 'company_id' => $company_id, 'describe' => '', 'create_time' => '', 'is_del' => 0, 'sort' => 0));
        $sub1 = array(array('id' => 0, 'name' => '全部', 'pid' => 0, 'company_id' => $company_id, 'describe' => '', 'create_time' => '', 'is_del' => 0, 'sort' => 0));
        $sub_list1 = array_merge($sub1, $sub_list, $sub);


        $data['list'] = $list2;
        $data['sub_list'] = $sub_list1;
        if ($list) {


            return apireturn(1, '成功', $data);


        } else {
            return apireturn(2, '暂无', []);
        }
    }

    public function user_echo()
    {
        $company_id = $_POST['company_id'];
        //所属部门
        $partment_list = db('department')->where(['company_id' => $company_id, 'is_del' => 0])->select();

        foreach ($partment_list as $k => $v) {
            if ($v['sort'] == 0) {
                $partment_list[$k]['sort'] = 9999;
            }
        }

        foreach ($partment_list as $key => $row) {
            $volume[$key] = $row['sort'];
            $edition[$key] = $row['create_time'];
        }
        array_multisort($volume, SORT_ASC, $edition, SORT_DESC, $partment_list);

        //职位
        $position_list = db('position')->where(['company_id' => $company_id])->select();
        $data['partment_list'] = $partment_list;
        $data['position_list'] = $position_list;
        return apireturn(1, '成功', $data);
    }

    //用户新增
    public function user_add()
    {
        $add_data['mobile'] = $_POST['mobile'];
        $add_data['account'] = $_POST['mobile'];
        $pattern = "/^1[123456789]\d{9}$/";
        $mobile = $_POST['mobile'];
        if (empty($mobile)) {
            return apireturn(2, '请输入手机号');
        } else {
            if (!preg_match($pattern, $mobile)) {
                return apireturn(2, '手机格式错误');
            }
        }
        $password = 12345678;
        //if(!$password){
        //    return apireturn(2,'密码为空');
        //}
        $add_data['password'] = thinkEncrypt($password);
        $add_data['username'] = $_POST['username'];
        // if(!$_POST['username']){
        //     return apireturn(2,'用户姓名为空');
        // }
        if (!$_POST['username'] || $_POST['username'] == undefined) {
            return apireturn(2, '用户姓名为空');
        }
        $data['company_id'] = $_POST['company_id'];
        if (!$_POST['company_id']) {
            return apireturn(2, '公司ID不能为空');
        }
        //用户角色 1:普通用户 2：管理员
        $data['role'] = $_POST['role'];
        if (!$_POST['role']) {
            return apireturn(2, '角色不能为空');
        }
        $data['department_id'] = $_POST['department_id'];
        if (!$_POST['department_id']) {
            return apireturn(2, '部门不能为空');
        }
        $data['position_id'] = $_POST['position_id'];
        if (!$_POST['position_id']) {
            return apireturn(2, '职位不能为空');
        }
        $data['create_time'] = time();
        $id = db('user')->where(['mobile' => $_POST['mobile']])->value('id');
        if ($id) {
            //已经存在
            $condition['uid'] = $id;
            $condition['company_id'] = $_POST['company_id'];
            $res = db('staff')->where($condition)->find();
            if ($res) {
                return apireturn(2, '此员工已存在，请勿重复添加', $res);
            } else {
                //这个员工虽然在用户表有，但是在这个公司不存在，添加到员工表
                $data['uid'] = $id;

                $userid = db('staff')->insertGetId($data);
                if ($userid) {
                    //新增成功，判断是不是管理员
                    //if($data['role']==2){
                    //   db('auth_group_access')->insert(['uid'=>$userid,'group_id'=>1]);//uid是staff表的ID
                    //}
                }

                return apireturn(1, '成功');
            }
        } else {
            $add_data['create_time'] = time();
            $res = db('user')->insertGetId($add_data);
            if ($res) {
                db('auth_group_access')->insert(['uid' => $res, 'group_id' => 1]);

                $data['uid'] = $res;

                $userid = db('staff')->insertGetId($data);
                if ($userid) {
                    //新增成功，判断是不是管理员
                    //if($data['role']==2){
                    //    db('auth_group_access')->insert(['uid'=>$userid,'group_id'=>1]);//uid是staff表的ID
                    //}
                }

                return apireturn(1, '成功', $res);
            } else {
                return apireturn(2, '失败');
            }
        }

    }

    public function register()
    {
        $add_data['mobile'] = $_POST['mobile'];
        $add_data['account'] = $_POST['mobile'];
        $add_data['username'] = $_POST['mobile'];
        $pattern = "/^1[123456789]\d{9}$/";
        $mobile = $_POST['mobile'];
        if (empty($mobile)) {
            return apireturn(2, '请输入手机号');
        } else {
            if (!preg_match($pattern, $mobile)) {
                return apireturn(2, '手机格式错误');
            }
        }

        $add_data['password'] = thinkEncrypt('12345678');

        // $add_data['username']=$_POST['username'];
        // if(!$_POST['username']){
        //     return apireturn(2,'用户姓名为空');
        // }

        $data['company_id'] = $_POST['company_id'];
        if (!$_POST['company_id']) {
            return apireturn(2, '公司ID不能为空');
        }
        //用户角色 1:普通用户 2：管理员
        $data['role'] = 1;
        if (!$data['role']) {
            return apireturn(2, '角色不能为空');
        }
        //意思是外编部门
        $data['department_id'] = 1;
        // if(!$_POST['department_id']){
        //     return apireturn(2,'部门不能为空');
        // }
        // $data['position_id']=$_POST['position_id'];
        // if(!$_POST['position_id']){
        //     return apireturn(2,'职位不能为空');
        // }
        $data['create_time'] = time();
        $id = db('user')->where(['mobile' => $_POST['mobile']])->value('id');
        if ($id) {
            //已经存在
            $condition['uid'] = $id;
            $condition['company_id'] = $_POST['company_id'];
            $res = db('staff')->where($condition)->find();
            if ($res) {
                return apireturn(2, '此员工已存在，请勿重复添加', $res);
            } else {
                //这个员工虽然在用户表有，但是在这个公司不存在，添加到员工表
                $data['uid'] = $id;

                $userid = db('staff')->insertGetId($data);
                if ($userid) {
                    //新增成功，判断是不是管理员
                    //if($data['role']==2){
                    //   db('auth_group_access')->insert(['uid'=>$userid,'group_id'=>1]);//uid是staff表的ID
                    //}
                }

                return apireturn(1, '注册成功');
            }
        } else {
            $add_data['username'] = $_POST['username'];
            $add_data['create_time'] = time();
            $res = db('user')->insertGetId($add_data);
            if ($res) {
                db('auth_group_access')->insert(['uid' => $res, 'group_id' => 1]);

                $data['uid'] = $res;

                $userid = db('staff')->insertGetId($data);
                if ($userid) {
                    //新增成功，判断是不是管理员
                    //if($data['role']==2){
                    //    db('auth_group_access')->insert(['uid'=>$userid,'group_id'=>1]);//uid是staff表的ID
                    //}
                }

                return apireturn(1, '注册成功', $res);
            } else {
                return apireturn(2, '失败');
            }
        }

    }

    //重置密码
    public function reset_password()
    {
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID为空');
        }
        $password = thinkEncrypt('12345678');
        $res = db('user')->where(['id' => $uid])->update(['password' => $password]);
        if ($res) {
            return apireturn(1, '成功', $res);
        } else {
            return apireturn(2, '失败');
        }
    }

    //我的
    public function my()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID为空');
        }
        $info = db('staff')->where(['uid' => $uid, 'company_id' => $company_id])->field('uid,status,create_time')->find();
        if (!$info) {
            return apireturn(2, '失败');
        }
        $info['create_time'] = date('Y-m-d H:i:s', $info['create_time']);
        if ($info['status'] == 1) {
            $info['status_name'] = '正常';
        } elseif ($info['status'] == 2) {
            $info['status_name'] = '锁定';
        } elseif ($info['status'] == 3) {
            $info['status_name'] = '禁用';
        }
        $info['username'] = db('user')->where(['id' => $uid])->value('username');
        $len = mb_strlen($info['username'], 'utf-8');
        if ($len > 11) {
            $info['username'] = mb_substr($info['username'], 0, 9, 'utf-8');
        } else {
            $info['username'] = $info['username'];
        }
        $info['mobile'] = db('user')->where(['id' => $uid])->value('mobile');
        $img = db('user')->where(['id' => $uid])->value('img');
        if ($img) {
            $info['img'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $img])->value('path');
        } else {
            $info['img'] = '';
        }
        //公司会员到期日期
        $service_expiration_time = db('company_introduction')->where(['id' => $company_id])->value('service_expiration_time');
        $info['service_expiration_time'] = date('Y-m-d H:i:s', $service_expiration_time);
        $openid = db('user')->where(['id' => $uid])->value('openid');
        $openid ? $info['openid'] = $openid : $info['openid'] = '';
        $seal_count = db('seal')->where(['company_id' => $company_id, 'is_del' => 0])->count();
        $price = C('SEAL_PRICE');
        $info['seal_count'] = $seal_count;
        $info['count_price'] = $seal_count * $price;
        $info['company_name'] = db('company_introduction')->where(['id' => $company_id])->value('name');

        $info['dd_userid'] = db('user')->where(['id' => $uid])->value('dd_userid');

        return apireturn(1, '成功', $info);
    }

    public function up_img()
    {
        if (empty($_FILES)) {
            return apiReturn(2, '请上传图片');
        } else {
            $file = $_FILES['file'];
            if (!is_dir("uploads/Picture/" . date("Y-m-d"))) {
                mkdir("uploads/Picture/" . date("Y-m-d"));
            }
            if (is_uploaded_file($file['tmp_name'])) {
                $str = stristr($file['name'], '.');
                $str = substr($str, 1);
                $avatar_path = "uploads/Picture/" . date("Y-m-d") . "/" . time() . rand(1000, 9999) . '.' . $str;
                if (copy($file['tmp_name'], $avatar_path)) {
                    $game_path = str_replace('Uploads/Picture/', 'game/headimage/', $avatar_path);
                    copy($file['tmp_name'], $game_path);
                    $cover['path'] = "/" . $avatar_path;
                    $cover['status'] = 1;
                    $cover['create_time'] = time();
                    $re = db('picture')->insertGetId($cover);
                    if ($re) {
                        $hh['imgurl'] = "http://" . $_SERVER['HTTP_HOST'] . $cover['path'];
                        $hh['imgid'] = $re;
                        $hh['name'] = $file['name'];
                        return apiReturn(1, '图片上传成功', $hh);
                    } else {
                        return apiReturn(2, '图片上传失败');
                    }
                } else {
                    return apiReturn(2, '图片上传失败');
                }
            }
        }
    }


    public function up_file123()
    {

        if (empty($_FILES)) {
            return apiReturn(2, '请上传图片');
        } else {
            $file = $_FILES['file'];
            if (!is_dir("Uploads/Picture/" . date("Y-m-d"))) {
                mkdir("Uploads/Picture/" . date("Y-m-d"));
            }
            if (is_uploaded_file($file['tmp_name'])) {
                // $str = stristr($file['name'], '.');
                // $str=substr($str,1);
                $name = $_POST['name'];
                $avatar_path = "Uploads/Picture/" . date("Y-m-d") . "/" . $name;
                // $file['tmp_name']=iconv('utf-8', 'gbk', $file['tmp_name']);
                // $avatar_path=iconv('utf-8', 'gbk', $avatar_path);
                if (copy($file['tmp_name'], $avatar_path)) {
                    // $game_path = str_replace('Uploads/Picture/','game/headimage/',$avatar_path);
                    // copy($file['tmp_name'],$game_path);
                    $cover['path'] = "/" . $avatar_path;
                    $cover['status'] = 1;
                    $cover['create_time'] = time();
                    $re = db('picture')->insertGetId($cover);
                    if ($re) {
                        $hh['imgurl'] = "http://" . $_SERVER['HTTP_HOST'] . $cover['path'];
                        $hh['imgid'] = $re;
                        $hh['name'] = $name;
                        return apiReturn(1, '图片上传成功', $hh);
                    } else {
                        return apiReturn(2, '图片上传失败');
                    }
                } else {
                    return apiReturn(2, '图片上传失败');
                }
            }
        }
    }


    public function up_file()
    {
        header("Content-type: text/html; charset=utf-8");
        $name = $_POST['name'];
        if (empty($_FILES)) {
            return apiReturn(2, '请上传图片');
        } else {
            $file = $_FILES['file'];
            if (!is_dir("Uploads/Picture/" . date("Y-m-d"))) {
                mkdir("Uploads/Picture/" . date("Y-m-d"));
            }
            if (is_uploaded_file($file['tmp_name'])) {
                $str = stristr($file['name'], '.');
                $str = substr($str, 1);
                $avatar_path = "Uploads/Picture/" . date("Y-m-d") . "/" . time() . rand(1000, 9999) . '.' . $str;
                if (copy($file['tmp_name'], $avatar_path)) {

                    $cover['path'] = "/" . $avatar_path;
                    $cover['status'] = 1;
                    $cover['create_time'] = time();
                    $cover['name'] = $name;
                    $re = db('picture')->insertGetId($cover);
                    file_put_contents('887.txt', print_r($re, true));
                    if ($re) {
                        $hh['imgurl'] = "http://" . $_SERVER['HTTP_HOST'] . $cover['path'];
                        $hh['imgid'] = $re;
                        $hh['name'] = $name;
                        file_put_contents('777.txt', print_r($hh['imgurl'], true));
                        return apiReturn(1, '图片上传成功', $hh);
                    } else {
                        return apiReturn(2, '图片上传失败');
                    }
                } else {
                    file_put_contents('787.txt', $name);
                    return apiReturn(2, '图片上传失败');
                }
            }
        }
    }


    public function copy()
    {
        header("Content-type: text/html; charset=utf-8");

        $list = M("region_manage a")->field('a.*,b.name as m_name')->join('left join pk_mechanism b on a.m_id = b.id')->order('create_time desc')->select();
        //echo'<pre>';print_r($list);die;
        foreach ($list as $k => $v) {
            $name = iconv('utf-8', 'gb2312', $v['name']);
            $file['tmp_name'] = "http://" . $_SERVER['HTTP_HOST'] . $v['qr_code'];
            $avatar_path = "Uploads/" . date("Y-m-d") . "/" . $name . '_' . $k . '.' . 'jpg';
            if (copy($file['tmp_name'], $avatar_path)) {

            } else {
            }

            //$name = iconv('utf-8','gb2312',$v['name']);
            //$file['tmp_name']="http://" . $_SERVER['HTTP_HOST'] .$v['entry_code'];
            //$avatar_path = "Uploads/" . date("Y-m-d") . "/" . $name.'_'.$k. '.'.'jpg' ;
            //if(copy($file['tmp_name'],$avatar_path)){

            //}

        }

    }


    //登录
    public function login()
    {
        $data = $_POST;
        $mobile = $_POST['mobile'];
        $pattern = "/^1[3456789]\d{9}$/";
        if (!preg_match($pattern, $mobile)) {
            return apireturn(2, '手机号码错误');
        }
        $password = $_POST['password'];
        if (!$password) {
            return apireturn(2, '密码不为空');
        }
        //print_r($_POST['is_login']);die;
        if ($mobile !== 18627673117) {
            if ($_POST['is_login'] != 1) {
                //不等于1说明是第一次登录
                if (empty($data['code'])) {

                    return apireturn('2', '验证码不能为空');
                }
                $result = db('sms_code')->where(array('phone' => $data['mobile']))->order('create_time desc')->find();
                if (empty($result)) {

                    return apireturn(2, '没有短信验证码信息');
                }
                if ($result['failure_time'] < time()) {

                    return apireturn(2, '短信验证码已过期');
                }
                if ($data['code'] != $result['code']) {

                    return apireturn(2, '短信验证码错误');
                }
            }
        }

        $config_password = thinkEncrypt($password);
        $info = db('user')->where(['mobile' => $mobile, 'password' => $config_password])->find();
        if (!$info) {
            return apireturn(2, '账号或者密码错误');
        } else {
            //$list=db('staff')->where(['uid'=>$info['id']])->group('company_id')->field('company_id,uid')->select();
            $list = db('staff')->alias('a')->join('company_introduction b', 'a.company_id=b.id', 'RIGHT')->where(['a.uid' => $info['id']])->group('a.company_id')->field('a.company_id,a.uid')->select();
            foreach ($list as $k => $v) {
                $list[$k]['name'] = db('company_introduction')->where(['id' => $v['company_id']])->value('name');
            }
        }
        return apiReturn(1, '成功', $list);
    }

    public function my_login()
    {
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID不能为空');
        }
        $list = db('staff')->alias('a')->join('company_introduction b', 'a.company_id=b.id', 'RIGHT')->where(['a.uid' => $uid])->group('a.company_id')->field('a.company_id,a.uid')->select();
        foreach ($list as $k => $v) {
            $list[$k]['name'] = db('company_introduction')->where(['id' => $v['company_id']])->value('name');
        }
        return apiReturn(1, '成功', $list);

    }

    //判断是否用户第一次再这个手机上登录
    public function first_login123()
    {
        $mobile = $_POST['mobile'];
        if (!$mobile) {
            return apireturn(2, '账号不能为空');
        }
        $uid = db('user')->where(['mobile' => $mobile])->value('id');
        if ($_POST['searchRecord']) {
            $searchRecord = $_POST['searchRecord'];
            $list = explode(',', $searchRecord);
            $id_list = explode(',', $uid);
            $res = array_intersect($list, $id_list);
            if ($res) {
                return apireturn(1, '存在');
            } else {
                return apireturn(2, '不存在');
            }
        } else {
            return apireturn(2, '不存在');
        }


    }

    public function first_login()
    {
        $mobile = $_POST['mobile'];
        if (!$mobile) {
            return apireturn(2, '账号不能为空');
        }
        if ($mobile == 18627673117) {
            return apireturn(1, '存在');
        } else {
            $uid = db('user')->where(['mobile' => $mobile])->value('id');
            if ($_POST['searchRecord']) {
                $searchRecord = $_POST['searchRecord'];
                $list = explode(',', $searchRecord);
                $id_list = explode(',', $uid);
                $res = array_intersect($list, $id_list);
                if ($res) {
                    return apireturn(1, '存在');
                } else {
                    return apireturn(2, '不存在');
                }
            } else {
                return apireturn(2, '不存在');
            }
        }


    }

    //用章申请(弃用)   申请次数：待审批  已审批中的申请表    用章次数是
    public function seal_application123()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID为空');
        }
        $condition['company_id'] = $company_id;
        $condition['uid'] = $uid;
        if ($_POST['start_time'] && $_POST['end_time']) {
            $condition['create_time'] = array('between', "$_POST[start_time],$_POST[end_time]");
        }
        $list = db('app_form')->where($condition)->group('seal_id')->order('create_time desc')->select();
        if ($list) {
            foreach ($list as $k => $v) {
                $application_list[$k]['name'] = db('seal')->where(['id' => $v['seal_id']])->value('name');
                //统计的是某个印章的所有申请次数，所有用章数量
                $condition['seal_id'] = $v['seal_id'];
                $application_list[$k]['count'] = db('app_form')->where($condition)->count();
                //因为只有申请次数，跟剩余次数，所以要先统计申请次数总数，减去剩余次数总数
                $number_list = db('app_form')->where($condition)->field('frequency,remaining_times')->select();
                foreach ($number_list as $kk => $vv) {
                    $application_list[$k]['frequency'] += $vv['frequency'];
                    $application_list[$k]['remaining_times'] += $vv['remaining_times'];
                }
                $application_list[$k]['used'] = $application_list[$k]['frequency'] - $application_list[$k]['remaining_times'];
                unset($application_list[$k]['frequency']);
                unset($application_list[$k]['remaining_times']);
            }
            return apireturn(1, '成功', $application_list);
        } else {
            return apireturn(2, '暂无', []);
        }
    }

    //用章申请
    public function seal_application()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }
        $condition['company_id'] = $company_id;
        if ($_POST['start_time'] && $_POST['end_time']) {
            $start_time = strtotime($_POST['start_time']);
            $end_time = strtotime($_POST['end_time'] . " 23:59:59");
            $condition['create_time'] = array('between', "$start_time,$end_time");
        }
        //status:5代表用章完成 没有用章完成的全在这个申请里面
        $condition['status'] = array('lt', 5);
        $list = db('app_form')->where($condition)->group('seal_id')->order('create_time desc')->select();
        if ($list) {
            foreach ($list as $k => $v) {
                $application_list[$k]['seal_id'] = $v['seal_id'];
                $application_list[$k]['name'] = db('seal')->where(['id' => $v['seal_id']])->value('name');
                //统计的是某个印章的没有用章完成的申请次数，所有没有用章完成表单的申请用章总数量
                $condition['seal_id'] = $v['seal_id'];
                $application_list[$k]['count'] = db('app_form')->where($condition)->count();
                $number_list = db('app_form')->where($condition)->field('frequency')->select();
                foreach ($number_list as $kk => $vv) {
                    $application_list[$k]['frequency'] += $vv['frequency'];
                }
            }
            return apireturn(1, '成功', $application_list);
        } else {
            return apireturn(2, '暂无', []);
        }
    }

    //申请明细
    public function application_details()
    {
        $seal_id = $_POST['seal_id'];
        if (!$seal_id) {
            return apireturn(2, '印章ID为空');
        }
        $condition['seal_id'] = $seal_id;
        $condition['status'] = array('lt', 5);

        $info = db('seal')->where(['id' => $seal_id])->find();
        if ($info['img']) {
            $info['img'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $info['img']])->value('path');
        } else {
            $info['img'] = '';
        }

        //起始时间  结束时间
        //
        if ($_POST['start_time'] && $_POST['end_time']) {
            $start_time = strtotime($_POST['start_time']);
            $end_time = strtotime($_POST['end_time'] . " 23:59:59");
            $condition['create_time'] = array('between', "$start_time,$end_time");
        }


        $list = db('app_form')->where($condition)->field('id,name,number,create_time,status')->order('id desc')->select();
        foreach ($list as $k => $v) {
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            if ($v['status'] == 1) {
                $list[$k]['status'] = '提交中';
            } elseif ($v['status'] == 2) {
                $list[$k]['status'] = '审核中';
            } elseif ($v['status'] == 3) {
                $list[$k]['status'] = '已拒绝';
            } elseif ($v['status'] == 4) {
                $list[$k]['status'] = '审核完成';
            } elseif ($v['status'] == 5) {
                $list[$k]['status'] = '用章完成';
            }
            $create_time = date('Y-m-d', $v['create_time']);
        }
        $info['start_time'] = $create_time;
        $info['end_time'] = date('Y-m-d', time());
        $data['list'] = $list;
        $data['info'] = $info;
        return apireturn(1, '成功', $data);
    }

    //用章明细
    public function use_details()
    {
        $seal_id = $_POST['seal_id'];
        if (!$seal_id) {
            return apireturn(2, '印章ID为空');
        }
        $condition['seal_id'] = $seal_id;
        $condition['status'] = array('egt', 5);

        $info = db('seal')->where(['id' => $seal_id])->find();
        if ($info['img']) {
            $info['img'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $info['img']])->value('path');
        } else {
            $info['img'] = '';
        }

        $start_time = $_POST['start_time'];
        $end_time = $_POST['end_time'];

        if ($start_time && $end_time) {
            $start_time = strtotime($_POST['start_time']);
            $end_time = strtotime($_POST['end_time'] . " 23:59:59");
            $condition['create_time'] = array('between', "$start_time,$end_time");
        }

        $list = db('app_form')->where($condition)->field('id,name,number,create_time,status')->order('id desc')->select();
        foreach ($list as $k => $v) {
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            if ($v['status'] == 1) {
                $list[$k]['status'] = '提交中';
            } elseif ($v['status'] == 2) {
                $list[$k]['status'] = '审核中';
            } elseif ($v['status'] == 3) {
                $list[$k]['status'] = '已拒绝';
            } elseif ($v['status'] == 4) {
                $list[$k]['status'] = '审核完成';
            } elseif ($v['status'] == 5) {
                $list[$k]['status'] = '用章完成';
            } elseif ($v['status'] == 6) {
                $list[$k]['status'] = '用章完成';
            }
            $create_time = date('Y-m-d', $v['create_time']);
        }
        $info['start_time'] = $create_time;
        $info['end_time'] = date('Y-m-d', time());
        $data['list'] = $list;
        $data['info'] = $info;
        return apireturn(1, '成功', $data);
    }

    //统计用章完成的申请表
    public function usage_statistics()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }
        $condition['company_id'] = $company_id;
        // if($_POST['start_time'] && $_POST['end_time']){
        //     $condition['create_time']=array('between', "$_POST[start_time],$_POST[end_time]");
        // }
        if ($_POST['start_time'] && $_POST['end_time']) {
            $start_time = strtotime($_POST['start_time']);
            $end_time = strtotime($_POST['end_time'] . " 23:59:59");
            $condition['create_time'] = array('between', "$start_time,$end_time");
        }
        //status:5代表用章完成 大于等于5
        $condition['status'] = array('egt', 5);
        $list = db('app_form')->where($condition)->group('seal_id')->order('create_time desc')->select();
        if ($list) {
            foreach ($list as $k => $v) {
                $application_list[$k]['name'] = db('seal')->where(['id' => $v['seal_id']])->value('name');
                //统计的是某个印章的没有用章完成的申请次数，所有没有用章完成表单的申请用章数量
                $application_list[$k]['seal_id'] = $v['seal_id'];
                $condition['seal_id'] = $v['seal_id'];
                $application_list[$k]['count'] = db('app_form')->where($condition)->count();
                //因为只有申请次数，跟剩余次数，所以要先统计申请次数总数，减去剩余次数总数
                $number_list = db('app_form')->where($condition)->field('frequency,used_times')->select();
                foreach ($number_list as $kk => $vv) {
                    //申请使用总次数（用章次数）
                    $application_list[$k]['frequency'] += $vv['frequency'];
                    //已用总次数（实际次数）
                    $application_list[$k]['used_times'] += $vv['used_times'];
                }
            }
            return apireturn(1, '成功', $application_list);
        } else {
            return apireturn(2, '暂无', []);
        }
    }


    //生成订单
    public function opens()
    {
        $uid = $_POST['uid'];
        if (!$uid) {
            return apiReturn(2, '用户ID为空');
        }
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apiReturn(2, '公司ID为空');
        }
        $data['order_number'] = "yz" . time() . $company_id;
        $data['price'] = 1;//后台配置的

        $data['company_id'] = $company_id;
        $data['uid'] = $uid;
        $data['create_time'] = time();


        $res = db('order')->insertGetId($data);
        if ($res) {
            $dat['order_number'] = $data['order_number'];
            $dat['id'] = $res;
            $this->xcxpay($dat['order_number']);//开发阶段，先跳过支付，直接成功
            return apiReturn(1, '成功', $dat);
        }
    }

    public function xcxpay($order_number)
    {
        vendor('wxpay.fact.jsapi');
        $Mode = new \JsApi();
        // print_r($Mode);die;

        $order_number = $order_number;
        //价格自己算
        $pe = db('order')->where(['order_number' => $order_number])->value('price');
        //$pe=0.01;
        $result = [];
        if ($pe > 0) {

            $uid = db('order')->where(['order_number' => $order_number])->value('uid');
            $openid = db('user')->where("id=$uid")->value('openid');

            $order_data["Body"] = '印章';
            $order_data["Attach"] = '';//附加数据；该数据也可为空字符串
            $order_data["trade_no"] = $order_number;
            $order_data["fee"] = $pe;

            $result = $Mode->pay_order($order_data, $openid);
            $result = json_decode($result, true);
        }

        if ($result) {
            return apiReturn(1, '支付成功', $result);
        } else {
            return apiReturn(2, '生成订单失败');
        }
    }

    /**
     * 支付回调
     * */
    public function notice()
    {

        $xml_data = file_get_contents("php://input");
        $data = json_encode(simplexml_load_string($xml_data, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($data, true);//转成数组

        //     $file='1121.txt';
        // file_put_contents($file,print_r($result,true));
        //接收附加数据
        $json_attach = $result['attach'];
        $attach_arr = json_decode($json_attach, true);

        //订单号
        $order_number = $result['out_trade_no'];
        if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
            //业务处理代码请自行实现
            $order_id = $order_number;//获取订单号

            $info = db('order')->where(['order_number' => $order_id])->find();
            if ($info['status'] == 1) {
                $res = db('order')->where(['order_number' => $order_id])->update(['status' => 2, 'pay_time' => time()]);
            }
            if ($res) {

                $reply = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                echo $reply;
                die();
            } else {
                $reply = "<xml><return_code><![CDATA[ERROR]]></return_code><return_msg><![CDATA[{$res['error']}]]></return_msg></xml>";
                echo $reply;
                die();
            }

        }
    }


    //公司介绍
    public function company_detail()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }
        $img = db('company_introduction')->where(['id' => $company_id])->value('img');
        if ($img) {
            $info['img'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where("id=$img")->value('path');
        } else {
            $info['img'] = '';
        }
        $list = db('company_detail_information')->where(['company_id' => $company_id])->order('sort asc , create_time asc')->select();

        //$data['content']=str_replace('<img src="','<img src='.'"http://'.$_SERVER['HTTP_HOST'],$data['content']);
        foreach ($list as $k => $v) {
            $list[$k]['content'] = str_replace('<img src="', '<img src=' . '"http://' . $_SERVER['HTTP_HOST'], $v['content']);
        }

        $info ? $data['info'] = $info : '';
        $list ? $data['list'] = $list : $data['list'] = [];
        return apireturn(1, '成功', $data);
    }

    public function content_detail()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '对象ID为空');
        }
        $content = db('company_detail_information')->where(['id' => $id])->value('content');
        $content = str_replace('<img src="', '<img src=' . '"http://' . $_SERVER['HTTP_HOST'], $content);
        return apireturn(1, '成功', $content);
    }

    //新闻动态
    public function news_information()
    {
        $type_list = db('news_class')->order('id asc')->select();
        if (!$type_list) {
            return apireturn(2, '暂无数据', []);
        }

        //新闻推荐
        $recommend_list = db('news_information')->where(['recommend' => 2])->select();
        if (!$recommend_list) {
            $recommend_list = db('news_information')->order('id desc')->select();
        }
        foreach ($recommend_list as $k => $v) {
            if ($v['re_img']) {
                $recommend_list[$k]['re_img'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $v['re_img']])->value('path');
            } else {
                if (!$v['img']) {
                    $recommend_list[$k]['re_img'] = '';
                } else {
                    $recommend_list[$k]['re_img'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $v['img']])->value('path');
                }

            }
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }

        $list = db('news_information')->order('sort desc,create_time desc')->where(['type_id' => $type_list[0]['id']])->order('id desc')->select();
        foreach ($list as $k => $v) {
            if ($v['img']) {
                $list[$k]['img'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $v['img']])->value('path');
            } else {
                $list[$k]['img'] = '';
            }
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }
        $data['type_list'] = $type_list;
        $data['list'] = $list;
        $data['recommend_list'] = $recommend_list;
        return apireturn(1, '成功', $data);
    }

    //点击新闻动态分类
    public function news_type()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '对象ID为空');
        }
        $list = db('news_information')->where(['type_id' => $id])->select();
        foreach ($list as $k => $v) {
            if ($v['img']) {
                $list[$k]['img'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $v['img']])->value('path');
            } else {
                $list[$k]['img'] = '';
            }
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }
        if ($list) {
            return apireturn(1, '成功', $list);
        } else {
            return apireturn(2, '暂无数据', []);
        }
    }

    //新闻动态详情
    public function news_detail()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '对象ID为空');
        }
        $data = db('news_information')->where(['id' => $id])->find();
        $data['content'] = str_replace('<img src="', '<img src=' . '"http://' . $_SERVER['HTTP_HOST'], $data['content']);
        $data['create_time'] = date('Y-m-d H:i:s', $data['create_time']);
        return apireturn(1, '成功', $data);
    }

    //获取下标ID
    public function rinfo()
    {
        $id = $_POST['id'];
        $recommend_list = db('news_information')->where(['recommend' => 2])->select();
        $tt = $recommend_list[$id];

        return apireturn(1, '成功', $tt);
    }

    //代理合作页面回显 也就是只显示页面的图文介绍
    public function agency_cooperation_echo()
    {
        $info = db('agency_cooperation_content')->find();
        if ($info['img']) {
            $info['img'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $info['img']])->value('path');
        } else {
            $info['img'] = '';
        }
        $info['mobile'] = C('MOBILE');

        return apireturn(1, '成功', $info);
    }

    public function agency_cooperation()
    {
        $data['uid'] = $_POST['uid'];
        $data['province'] = $_POST['province'];
        $data['city'] = $_POST['city'];
        $data['area'] = $_POST['area'];
        $data['mobile'] = $_POST['mobile'];
        if (!$_POST['mobile']) {
            return apireturn(2, '联系号码不能为空');
        }
        $data['company_name'] = $_POST['company_name'];
        if (!$_POST['company_name']) {
            return apireturn(2, '公司名称不能为空');
        }
        $data['company_address'] = $_POST['company_address'];
        if (!$_POST['company_address']) {
            return apireturn(2, '公司地址不能为空');
        }
        $data['create_time'] = time();
        $res = db('agency_cooperation')->insertGetId($data);
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    //信息设置
    public function information_settings()
    {
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID为空');
        }
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID为空');
        }
        $info = db('staff')->where(['uid' => $uid, 'company_id' => $company_id])->field('department_id,uid,status,create_time,position_id,role')->find();
        $department = explode(',', $info['department_id']);
        if ($department) {
            foreach ($department as $k => $v) {
                if ($k == 0) {
                    $name = db('department')->where(['id' => $v])->value('name');
                } else {
                    $name .= ',' . db('department')->where(['id' => $v])->value('name');
                }
            }
            $info['partment_name'] = $name;
        } else {
            $info['partment_name'] = '';
        }
        // $info['partment_name']=db('department')->where(['id'=>$department[0]])->value('name');
        $info['mobile'] = db('user')->where(['id' => $info['uid']])->value('mobile');
        $info['username'] = db('user')->where(['id' => $info['uid']])->value('username');
        $position_name = db('position')->where(['id' => $info['position_id']])->value('name');
        if (!$position_name) {
            $info['position_name'] = '';
        } else {
            $info['position_name'] = $position_name;
        }
        $info['create_time'] = date('Y-m-d H:i:s', $info['create_time']);
        $img = db('user')->where(['id' => $info['uid']])->value('img');
        $info['img'] = $img;
        if ($img) {
            $info['imgs'] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where("id=$img")->value('path');
        } else {
            $info['imgs'] = '';
        }
        if ($info['status'] == 1) {
            $info['status_name'] = '正常';
        } elseif ($info['status'] == 2) {
            $info['status_name'] = '锁定';
        } elseif ($info['status'] == 3) {
            $info['status_name'] = '禁用';
        }


        $data['info'] = $info;
        //print_r($info['role']);die;
        $data['index'] = $info['role'] - 1;
        $data['index123'] = $info['status'] - 1;
        //所属部门
        $partment_list = db('department')->where(['company_id' => $company_id, 'is_del' => 0])->select();

        foreach ($partment_list as $k => $v) {
            if ($v['sort'] == 0) {
                $partment_list[$k]['sort'] = 9999;
            }
        }

        foreach ($partment_list as $key => $row) {
            $volume[$key] = $row['sort'];
            $edition[$key] = $row['create_time'];
        }
        array_multisort($volume, SORT_ASC, $edition, SORT_DESC, $partment_list);
        //echo '<pre>';print_r($department);die;
        foreach ($partment_list as $k => $v) {
            foreach ($department as $kk => $vv) {
                if ($v['id'] == $vv) {
                    $v['ck'] = 1;
                }
            }
            $partment_list[$k] = $v;
        }
        //职位
        $position_list = db('position')->where(['company_id' => $company_id])->select();
        $data['partment_list'] = $partment_list;
        $data['position_list'] = $position_list;
        $ids = array_column($position_list, 'id');
        //当前ID的下标值
        $key = array_search($info['position_id'], $ids);

        $data['index456'] = $key;


        return apireturn(1, '成功', $data);


        //return apireturn(1,'成功',$info);
    }

    //保存
    public function save_setting14()
    {
        file_put_contents('987.txt', print_r($_POST, true));
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '对象ID为空');
        }
        $username = $_POST['username'];
        if (!$username) {
            return apireturn(2, '失败');
        }
        $img = $_POST['img'];
        $res = db('user')->where(['id' => $uid])->update(['username' => $username, 'img' => $img]);
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    public function save_setting()
    {
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '对象ID为空');
        }
        $username = $_POST['username'];
        $role = $_POST['role'];
        $department_id = $_POST['department_id'];
        $position_id = $_POST['position_id'];
        $company_id = $_POST['company_id'];
        $img = $_POST['img'];
        $res = db('user')->where(['id' => $uid])->update(['username' => $username, 'img' => $img]);
        $re = db('staff')->where(['uid' => $uid, 'company_id' => $company_id])->update(['role' => $role, 'department_id' => $department_id, 'position_id' => $position_id, 'status' => $_POST['status']]);
        if ($res || $re) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    //更改密码
    public function change_password()
    {
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID不能为空');
        }
        $password = $_POST['password'];
        if (!$password) {
            return apireturn(2, '原密码不能为空');
        }
        $new_password = $_POST['new_password'];
        if (!$new_password) {
            return apireturn(2, '新密码不能为空');
        }
        $confirm_password = $_POST['confirm_password'];
        if (!$confirm_password) {
            return apireturn(2, '确认密码不能为空');
        }
        $info_password = db('user')->where(['id' => $uid])->value('password');
        $pp = thinkEncrypt($password);
        if ($pp !== $info_password) {
            return apireturn(2, '原密码错误');
        } elseif ($new_password !== $confirm_password) {
            return apireturn(2, '新密码跟确认密码不一致');
        }

        $length = strlen($new_password);
        if ($length < 6) {
            return apireturn(2, '密码不能小于6位');
        }


        $nn = thinkEncrypt($new_password);
        $res = db('user')->where(['id' => $uid])->update(['password' => $nn]);
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    //产品宣传
    public function product_publicity()
    {
        $video = db('product_publicity')->value('video');
        if (!$video) {
            return apireturn(2, '失败');
        }
        return apireturn(1, '成功', $video);
    }

    //退出登录
    public function loginout()
    {
        session_destroy();
        return apireturn(1, '成功');
    }

    public function getWxUserInfo()
    {
        $input = $_POST;
        file_put_contents('720.txt', $input);
        $code = $input['code'];
        $encryptedData = $input['encryptedData'];
        $iv = $input['iv'];
        if (empty($code)) return api_return(2, 'code不能为空');
        if (empty($encryptedData)) return api_return(2, 'encryptedData不能为空');
        if (empty($iv)) return api_return(2, 'iv不能为空');

        $appid = 'wxbc7aca851ac61a98';
        $secret = 'a797a1b4a0efcfb050b607ce0ced5558';
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';
        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);

        $url = $url . $param_str;
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
        $user_data = curl_exec($curl);                     //返回api的json对象
        //关闭URL请求
        curl_close($curl);

        $member_data = json_decode($user_data, true);
        file_put_contents('455555555.txt', print_r($member_data, true));
        $openid = $member_data['openid'];
        $unionid = $member_data['unionid'];
        $user_data = json_decode($user_data);

        $session_key = $this->define_str_replace($user_data->session_key);
        $session_key = stripslashes($session_key);

        $user_info = "";
        vendor('wxApp.wxBizDataCrypt');//引入微信解密文件
        $wxBizDataCrypt = new \WXBizDataCrypt($appid, $session_key);

        $errCode = $wxBizDataCrypt->decryptData($encryptedData, $iv, $user_info);

        if ($errCode !== 0) {

            return apireturn(2, '失败', $errCode);
        }
        file_put_contents('7777777.txt', print_r($user_info, true));
        $user_info = json_decode($user_info, true);
        file_put_contents('888888.txt', print_r($user_info, true));
        $user_info['session_key'] = $session_key;
        $user_info['openid'] = $openid;
        $user_info['unionid'] = $unionid;
        return apireturn(1, '成功', $user_info);
    }


    function define_str_replace($data)

    {

        return str_replace(' ', '+', $data);

    }

    //更新openid
    public function save_openid()
    {
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID不能为空');
        }
        $openid = $_POST['openid'];
        $unionid = $_POST['unionid'];
        //print_r($uid);die;
        if (!$openid) {
            return apireturn(2, 'OPENID不能为空');
        }
        //$res=db('user')->where(['id'=>$uid])->update(['openid'=>$openid,'unionid'=>$unionid]);

        //判断是不是先关注的公众号
        $app_openid = db('user')->where(['unionid' => $unionid])->value('app_openid');

        if ($app_openid) {

            //db('user')->where(['app_openid'=>$app_openid])->delete();
        } else {
            $app_openid = '';
        }
        $res = db('user')->where(['id' => $uid])->update(['openid' => $openid, 'unionid' => $unionid, 'app_openid' => $app_openid]);

        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    //用章页面
    public function yz_detail()
    {
        $app_id = $_POST['app_id'];
        if (!$app_id) {
            return apireturn(2, '失败');
        }
        $info = db('app_form')->where(['id' => $app_id])->find();
        $info['device_name'] = db('seal')->where(['id' => $info['seal_id']])->value('number');
        $info['seal_name'] = db('seal')->where(['id' => $info['seal_id']])->value('name');

        $use_log = Db::name('use_log')->select();
        $info['use_log'] = $use_log ? : [];

        return apireturn(1, '成功', $info);
    }
    //用章
    // public function use_seal(){
    //     $app_id=$_POST['app_id'];
    //     if(!$app_id){
    //         return apireturn(2,'对象ID为空');
    //     }
    //     //申请表单ID
    //     $info=db('app_form')->where(['id'=>$app_id])->find();
    //     if(!$info){
    //         return apireturn(2,'失败');
    //     }
    //     if($info['status'] !== 4){
    //         return apireturn(2,'状态错误');
    //     }
    //     $seal_info['name']=db('seal')->where(['id'=>$info['seal_id']])->value('name');
    //     $seal_info['frequency']=$info['frequency'];
    //     $seal_info['remaining_times']=$info['remaining_times'];
    //     return apireturn(1,'成功',$seal_info);
    // }

    //机器盖章触发事件
    public function machine_seal()
    {
        $app_id = $_POST['app_id'];
        if (!$app_id) {
            return apireturn(2, '对象ID为空');
        }
        $time = time();
        $info = db('app_form')->where(['id' => $app_id])->find();

        if ($info['remaining_times'] == 1) {
            db('app_form')->where(['id' => $app_id])->update(['status' => 5]);
        }
        if ($info['remaining_times'] < 1) {
            //可用次数少于1  就不能使用了
            $data['uid'] = $info['uid'];
            $data['app_id'] = $info['app_id'];
            $data['seal_id'] = $info['seal_id'];
            $data['reason'] = 1;
            $data['create_time'] = $time;
            db('alarm_record')->insert($data);

            return apireturn(2, '盖章次数超过');
        } else {
            $add_data['app_form'] = $app_id;
            $add_data['create_time'] = $time;
            db('use_record')->insert($add_data);
            //已用次数加已
            if ($info['remaining_times'] < 1) {
                $data['uid'] = $info['uid'];
                $data['app_id'] = $info['app_id'];
                $data['seal_id'] = $info['seal_id'];
                $data['reason'] = 1;
                $data['create_time'] = $time;
                db('alarm_record')->insert($data);
                return apireturn(2, '盖章次数超过');
            }
            db('app_form')->where(['id' => $app_id])->setInc('used_times', 1);
            //可用次数
            db('app_form')->where(['id' => $app_id])->setDec('remaining_times', 1);
            db('app_form')->where(['id' => $app_id])->update(['chapter_time' => $time]);
            $info = db('app_form')->where(['id' => $app_id])->find();
        }
        return apireturn(1, '成功', $info);
    }

    /**
     * 印章之后一个使用机会的时候，按下印章直接调用这个接口
     * */
    public function onlyOneCountSeal()
    {
        $input = Request()->param();

        $app_id = $input['app_id'];      // 印章申请记录ID

        if (empty($app_id)) apiReturn(2, '印章申请记录ID缺失');

        $info = db('app_form')->where(['id' => $app_id])->find();

        $used_times = 1;
        $frequency = $info['frequency'];
        $remaining_times = $frequency - $used_times;
        $data = [
            'status' => 5,
            'used_times' => $used_times,
            'remaining_times' => $remaining_times,
            'chapter_time' => time()
        ];
        Db::name('app_form')->where(['id' => $app_id])->update($data);

        file_put_contents(RUNTIME_PATH . 'only.txt', Db::name('app_form')->getLastSql());
    }

    /**
     * 同步印章使用记录
     * */
    public function sealUseLog()
    {
        $input = Request()->param();

        $app_id = $input['app_id'];      // 印章申请记录ID
        $use_count = $input['use_count'];// 使用次数

        if ($app_id) {
            $count = Db::name('use_log')->where(['app_id' => $app_id])->count();

            if ($count) {
                Db::name('use_log')->where(['app_id' => $app_id])->setField('use_count', $use_count);
            } else {
                $data = [
                    'app_id' => $app_id,
                    'use_count' => $use_count
                ];
                Db::name('use_log')->insert($data);
            }
        }
    }

    /**
     * 将印章使用记录缓存数据同步到数据库
     * */
    public function syncSealUseLog()
    {
        $input = Request()->param();

        $use_log = json_decode($input['use_log'], true);
        if ($use_log) {
            foreach ($use_log as &$v) {
                $app_id = $v['app_id'];
                $use_count = $v['use_count'];

                $count = Db::name('use_log')->where(['app_id' => $app_id])->count();

                if ($count) {
                    Db::name('use_log')->where(['app_id' => $app_id])->setField('use_count', $use_count);
                } else {
                    $data = [
                        'app_id' => $app_id,
                        'use_count' => $use_count
                    ];
                    Db::name('use_log')->insert($data);
                }
            }
        }
    }

    //点击结束用章
    public function closing_seal()
    {
        $app_id = $_POST['app_id'];
        if (!$app_id) {
            return apireturn(2, '对象ID为空');
        }
        $res = db('app_form')->where(['id' => $app_id])->update(['status' => 5]);
        //if($res){

        //点击结束用章我就要生成一条延时任务判断24小时之后有没有上传图片，没有就锁定账户
        $info = db('app_form')->where(['id' => $app_id])->find();
        $params['form_id'] = $app_id;
        $params['uid'] = $info['uid'];
        $params['company_id'] = $info['company_id'];
        $params['status'] = 2;//1是上传图片 24小时之后变状态   2：是判断24小时之后有没有上传图片去锁定用户
        $time = 60 * 60 * 24;
        $isPushed = Queue::later($time, Constants::$DELAY_QUEUE['handler'], $params, Constants::$DELAY_QUEUE['queue']);

        // 删除印章同步记录
        Db::name('use_log')->where(['app_id' => $app_id])->delete();

        return apireturn(1, '成功', $app_id);
        //}else{
        //    return apireturn(2,'失败');
        //}
    }

    public function closing_seal123()
    {
        $app_id = $_POST['app_id'];
        if (!$app_id) {
            return apireturn(2, '对象ID为空');
        }
        $res = db('app_form')->where(['id' => $app_id])->update(['status' => 5]);
        //if($res){

        //点击结束用章我就要生成一条延时任务判断24小时之后有没有上传图片，没有就锁定账户
        $info = db('app_form')->where(['id' => $app_id])->find();
        $params['form_id'] = $app_id;
        $params['uid'] = $info['uid'];
        $params['company_id'] = $info['company_id'];
        $params['status'] = 2;//1是上传图片 24小时之后变状态   2：是判断24小时之后有没有上传图片去锁定用户
        $time = 60 * 60 * 24;
        $isPushed = Queue::later($time, Constants::$DELAY_QUEUE['handler'], $params, Constants::$DELAY_QUEUE['queue']);

        // 删除印章同步记录
        Db::name('use_log')->where(['app_id' => $app_id])->delete();

        return apireturn(1, '成功', $app_id);
        //}else{
        //    return apireturn(2,'失败');
        //}
    }

    public function closing_seal123_experience()
    {
        $app_id = $_POST['app_id'];
        if (!$app_id) {
            return apireturn(2, '对象ID为空');
        }
        $use_count = $_POST['use_count'] ? : 0;

        $res = db('app_form')->where(['id' => $app_id])->update(['status' => 5]);
        //if($res){

        //点击结束用章我就要生成一条延时任务判断24小时之后有没有上传图片，没有就锁定账户
        $info = db('app_form')->where(['id' => $app_id])->find();
        $params['form_id'] = $app_id;
        $params['uid'] = $info['uid'];
        $params['company_id'] = $info['company_id'];
        $params['status'] = 2;//1是上传图片 24小时之后变状态   2：是判断24小时之后有没有上传图片去锁定用户
        $time = 60 * 60 * 24;
        $isPushed = Queue::later($time, Constants::$DELAY_QUEUE['handler'], $params, Constants::$DELAY_QUEUE['queue']);

        $frequency = $info['frequency'];

        $remaining_times = $frequency - $use_count;
        Db::name('app_form')->where(['id' => $app_id])->update(['used_times' => $use_count, 'remaining_times' => $remaining_times, 'chapter_time' => time()]);
        Db::name('use_log')->where(['app_id' => $app_id])->delete();

        return apireturn(1, '成功', $app_id);
        //}else{
        //    return apireturn(2,'失败');
        //}
    }

    //暂停用章是关闭蓝牙 断开连接    结束用章也是关闭蓝牙 断开连接
    //用章完成上传图片
    public function use_seal_img()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '表单ID为空');
        }
        $imgs = $_POST['imgs'];
        if (!$imgs) {
            return apireturn(2, '图片不能为空');
        }
        $res = db('app_form')->where(['id' => $id])->update(['used_img' => $imgs]);
        if ($res) {
            //上传图片完成，就要改变表单状态
            //db('app_form')->where(['id'=>$id])->update(['status'=>6]);
            db('approval_process')->where(['form_id' => $id])->update(['form_state' => 2]);

            $params['form_id'] = $id;
            $time = 60 * 60 * 24;
            //$time=20;
            $params['status'] = 1;//1是上传图片 24小时之后变状态   2：是判断24小时之后有没有上传图片去锁定用户
            $isPushed = Queue::later($time, Constants::$DELAY_QUEUE['handler'], $params, Constants::$DELAY_QUEUE['queue']);

            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }


    public function use_seal_img726()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '表单ID为空');
        }
        $imgs = $_POST['imgs'];
        // if(!$imgs){
        //     return apireturn(2,'图片不能为空');
        // }
        if (!$imgs) {
            return apireturn(2, '图片不能为空');
        }
        $used_file = $_POST['used_file'];


        $res = db('app_form')->where(['id' => $id])->update(['used_img' => $imgs, 'used_file' => $used_file]);
        if ($res) {
            //上传图片完成，就要改变表单状态
            //db('app_form')->where(['id'=>$id])->update(['status'=>6]);
            db('approval_process')->where(['form_id' => $id])->update(['form_state' => 2]);

            $params['form_id'] = $id;
            $time = 60 * 60 * 24;
            //$time=20;
            $params['status'] = 1;//1是上传图片 24小时之后变状态   2：是判断24小时之后有没有上传图片去锁定用户
            $isPushed = Queue::later($time, Constants::$DELAY_QUEUE['handler'], $params, Constants::$DELAY_QUEUE['queue']);

            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    public function img_detail()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '表单ID为空');
        }
        $frequency = db('app_form')->where(['id' => $id])->value('frequency');
        // 删除印章同步记录
        $used_times = db('use_log')->where(['app_id' => $id])->value('use_count');
        if ($used_times) {
            // $remaining_times=$info['frequency']-$used_times;
            $remaining_times = $frequency - $used_times;
            Db::name('app_form')->where(['id' => $id])->update(['used_times' => $used_times, 'remaining_times' => $remaining_times, 'chapter_time' => time()]);
            Db::name('use_log')->where(['app_id' => $id])->delete();
        }


        $info = db('app_form')->where(['id' => $id])->find();
        if ($info['used_img']) {
            $imgs = explode(',', $info['used_img']);
            $data['picid'] = $imgs;

            foreach ($imgs as $k => $v) {
                $path[] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where("id=$v")->value('path');
            }
            $data['picPaths'] = $path;
            $data['cz'] = 1;
        } else {
            $data['picid'] = [];
            $data['picPaths'] = [];
            $data['cz'] = 2;
        }

        if ($info['used_file']) {
            $imgs = explode(',', $info['used_file']);
            $data['filepicid'] = $imgs;

            foreach ($imgs as $k => $v) {
                $path[] = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where("id=$v")->value('path');
                $name[] = db('picture')->where("id=$v")->value('name');
            }
            $data['filepicname'] = $name;
            $data['filepicPaths'] = $path;
            $data['cz1'] = 1;
        } else {
            $data['filepicid'] = [];
            $data['filepicPaths'] = [];
            $data['filepicname'] = [];
            $data['cz1'] = 2;
        }

        return apireturn(1, '成功', $data);
    }

    //服务续费
    public function service_renewal()
    {

    }

    //send发送订阅通知
    public function send_subscribe123()
    {
        //https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend?access_token=ACCESS_TOKEN
        $openid = "olYx_6lySQhGH8WlJzY9NWxmOb1s";
        $appid1 = 'wxbc7aca851ac61a98';               //微信appid
        $secret1 = 'a797a1b4a0efcfb050b607ce0ced5558';//微信密钥

        $appid = 'wx14f0e22861952e28';               //公众号appid
        $secret = '11dd50a502bdb002860bf494e1e78d72';//公众号密钥
        $TEMPLATEID = "Loe00icdsWKrGjTENZUlPODrW3q1sZxGbDmKbMB6vzI";
        $access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret), true)['access_token'];
        print_r($access_token);
        die;
        // {
        //       "touser": "OPENID",
        //       "template_id": "TEMPLATEID",
        //       "page": "mp.weixin.qq.com",
        //       "miniprogram":{
        //                  "appid":"APPID",
        //                  "pagepath":"index?foo=bar"
        //       },
        //       "data": {
        //           "name1": {
        //               "value": "广州腾讯科技有限公司"
        //           },
        //           "thing8": {
        //               "value": "广州腾讯科技有限公司"
        //           },
        //            "time7": {
        //               "value": "2019年8月8日"
        //           }
        //          }
        //     }
        //     ["operation"=>"Request","fromUserId"=>$uid,"toUserId"=>$friend_id,"message"=>"我是" . $nickname . "，能加下好友吗？","extra"=>["sourceUserNickname"=>$nickname]];
        $con = ["touser" => $openid, "template_id" => $TEMPLATEID, "page" => "", "miniprogram" => ["appid" => $appid1, "pagepath" => "index?foo=bar"], "data" => ["name" => ["value" => "同创未来"]]];
        $data = json_encode($con);

        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend?access_token=$access_token";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 'image/gif');
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果需要将结果直接返回到变量里，那加上这句。
        $res = curl_exec($ch);

        return apireturn(1, '成功', $res);

    }

    //send发送订阅通知
    public function send_subscribe123456($openid, $uid)
    {
        //https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend?access_token=ACCESS_TOKEN
        //$openid="olYx_6lySQhGH8WlJzY9NWxmOb1s-B96UOBoW_8";

        $appid1 = 'wxbc7aca851ac61a98';//微信appid
        // $secret = 'a797a1b4a0efcfb050b607ce0ced5558';//微信密钥

        $appid = 'wx14f0e22861952e28';               //公众号appid
        $secret = '11dd50a502bdb002860bf494e1e78d72';//公众号密钥

        $template_id = "rdrFT83yHHpPcRvPVCoc9KM5QVsH6BqWrljhyw5sqjk";
        $access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret), true)['access_token'];
        //print_r($access_token);die;
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $data = [
            "touser" => "olYx_6lySQhGH8WlJzY9NWxmOb1s",
            "template_id" => "rdrFT83yHHpPcRvPVCoc9KM5QVsH6BqWrljhyw5sqjk",
            "url" => "",
            "miniprogram" => [
                "appid" => "wxbc7aca851ac61a98",
                "path" => "pages/login/login"
            ],
            "topcolor" => "#FF0000",

            "data" => [
                "first" => [
                    "value" => "您好，有新的用章申请需要审核",
                    "color" => "#173177"
                ],
                "keyword1" => [
                    "value" => "tzb",
                    "color" => "#173177"
                ],
                "keyword2" => [
                    "value" => "技术部",
                    "color" => "#173177"
                ],
                "keyword3" => [
                    "value" => "合同章",
                    "color" => "#173177"
                ],
                "keyword4" => [
                    "value" => "用途",
                    "color" => "#173177"
                ],
                "keyword5" => [
                    "value" => "文件名称",
                    "color" => "#173177"
                ],
                "remark" => [
                    "value" => "可点击详情直接审核。",
                    "color" => "#173177"
                ]
            ]
        ];


        $data = json_encode($data, JSON_UNESCAPED_UNICODE);

        httpsRequest($url, $data);

    }

    public function send_subscribe($openid, $uid, $form_id)
    {

        $username = db('user')->where(['id' => $uid])->value('username');
        $department_id = db('staff')->where(['uid' => $uid])->value('department_id');
        $list = explode(',', $department_id);
        $d_id = $list[0];
        $partment_name = db('department')->where(['id' => $d_id])->value('name');
        $seal_id = db('app_form')->where(['id' => $form_id])->value('seal_id');
        $name = db('app_form')->where(['id' => $form_id])->value('name');
        $seal_type = db('seal')->where(['id' => $seal_id])->value('seal_type');
        $configModel = new \app\admin\model\Config();
        $res = $configModel->getConfigCacheByName(Constants::$SEAL_TYPE_KEY);
        $type_list = array_merge($res);
        if ($seal_type == 1) {
            $type_name = $type_list[0]['name'];
        } elseif ($seal_type == 2) {
            $type_name = $type_list[1]['name'];
        } elseif ($seal_type == 3) {
            $type_name = $type_list[2]['name'];
        } elseif ($seal_type == 4) {
            $type_name = $type_list[3]['name'];
        }
        $appid1 = 'wxbc7aca851ac61a98';//微信appid

        $appid = 'wx14f0e22861952e28';               //公众号appid
        $secret = '11dd50a502bdb002860bf494e1e78d72';//公众号密钥

        $template_id = "rdrFT83yHHpPcRvPVCoc9KM5QVsH6BqWrljhyw5sqjk";
        $access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret), true)['access_token'];
        //print_r($access_token);die;
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $data = [
            "touser" => $openid,
            "template_id" => "rdrFT83yHHpPcRvPVCoc9KM5QVsH6BqWrljhyw5sqjk",
            "url" => "",
            "miniprogram" => [
                "appid" => "wxbc7aca851ac61a98",
                "path" => "pages/cd_wdsh/cd_wdsh"
            ],
            "topcolor" => "#FF0000",

            "data" => [
                "first" => [
                    "value" => "您好，有新的用章申请需要审核",
                    "color" => "#173177"
                ],
                "keyword1" => [
                    "value" => $username,
                    "color" => "#173177"
                ],
                "keyword2" => [
                    "value" => $partment_name,
                    "color" => "#173177"
                ],
                "keyword3" => [
                    "value" => $type_name,
                    "color" => "#173177"
                ],
                "keyword4" => [
                    "value" => '审核用章',
                    "color" => "#173177"
                ],
                "keyword5" => [
                    "value" => $name,
                    "color" => "#173177"
                ],
                "remark" => [
                    "value" => "可点击详情直接审核。",
                    "color" => "#173177"
                ]
            ]
        ];


        $data = json_encode($data, JSON_UNESCAPED_UNICODE);

        httpsRequest($url, $data);

    }


    public function send_subscribe31($openid, $uid, $form_id)
    {
        $form_name = db('app_form')->where(['id' => $form_id])->value('name');
        $username = db('user')->where(['id' => $uid])->value('username');
        $tt = db('app_form')->where(['id' => $form_id])->value('create_time');
        $time = date('Y-m-d H:i:s', $tt);
        $appid1 = 'wxbc7aca851ac61a98';//微信appid

        $appid = 'wx14f0e22861952e28';               //公众号appid
        $secret = '11dd50a502bdb002860bf494e1e78d72';//公众号密钥

        $template_id = "gOE5AyQ_TYTBzfvUuKuzylbg8Km6m226qynoM2fEaHo";
        $access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret), true)['access_token'];
        //print_r($access_token);die;
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $data = [
            "touser" => $openid,
            "template_id" => "gOE5AyQ_TYTBzfvUuKuzylbg8Km6m226qynoM2fEaHo",
            "url" => "",
            "miniprogram" => [
                "appid" => "wxbc7aca851ac61a98",
                "path" => "pages/cd_wdsq/cd_wdsq"
            ],
            "topcolor" => "#FF0000",

            "data" => [
                "first" => [
                    "value" => "用章申请完成提醒",
                    "color" => "#173177"
                ],
                "keyword1" => [
                    "value" => $form_name,
                    "color" => "#173177"
                ],
                "keyword2" => [
                    "value" => $username,
                    "color" => "#173177"
                ],
                "keyword3" => [
                    "value" => $time,
                    "color" => "#173177"
                ],
                "keyword4" => [
                    "value" => '通过',
                    "color" => "#173177"
                ]
            ]
        ];


        $data = json_encode($data, JSON_UNESCAPED_UNICODE);

        httpsRequest($url, $data);

    }

    //存到阿里的数据库去
    public function test()
    {

        $form_id = $_POST['form_id'];
        if (!$form_id) {
            return apireturn(2, '表单ID为空');
        }
        //当前审核人
        $condition['form_id'] = $form_id;
        //$condition['status']=array('eq',1);


        $condition['number_of_submissions'] = db('approval_process')->where($condition)->order('id desc')->value('number_of_submissions');
        $list = db('approval_process')->where($condition)->order('id asc')->select();
        foreach ($list as $k => $v) {
            $reviewer_name .= ',' . db('user')->where(['id' => $v['uid']])->value('username');
        }
        $reviewer = substr($reviewer_name, 1);

        $info = db('app_form')->where(['id' => $form_id])->find();
        $create_time = date('Y-m-d H:i:s', $info['create_time']);
        $seal_name = db('seal')->where(['id' => $info['seal_id']])->value('name');
        $username = db('user')->where(['id' => $info['uid']])->value('username');
        $chapter_time = date('Y-m-d H:i:s', $info['chapter_time']);


        // 初始化客户端
        $client = new AntCloudClient(
            "https://openapi.antchain.antgroup.com/gateway.do",
            "LTAI5tNciJJufZqWRs6tTpP6",
            "q5p5FA6gvXg49aae04QLUSQ8JGPnLZ"
        );

        $attrbuites = [];
        $attrbuites[] = ['name' => "id", "value" => $form_id];
        $attrbuites[] = ['name' => "username", "value" => $reviewer];
        $attrbuites[] = ['name' => "applyTime", "value" => $create_time];
        $attrbuites[] = ['name' => "name", "value" => $seal_name];
        $attrbuites[] = ['name' => "applyUser", "value" => $username];
        $attrbuites[] = ['name' => "applyCount", "value" => $info['frequency']];
        $attrbuites[] = ['name' => "useCount", "value" => $info['used_times']];
        $attrbuites[] = ['name' => "fileName", "value" => $info['name']];
        $attrbuites[] = ['name' => "useTime", "value" => $chapter_time];

        // 构建请求
        $request = array(
            "app_did" => "did:mychain:19c3051eba145e47e92209bf9d9ddcdf6cb7b1ad4c24b6991a4e85e4bfe8f59b",
            "schema_name" => "testTwo",
            "attributes" => $attrbuites,
            "method" => "blockchain.appex.solution.fastnotary.save",
            "version" => "1.0",
            "product_instance_id" => "appex",
            "region_name" => "CN-HANGZHOU-FINANCE",
        );

        // 发送调用请求，解析响应结果
        $response = $client->execute($request);
        //echo "<pre>";
        //print_r($response);exit;

        //存到数据库去了  然后要生成二维码把他取出来
        $this->test2($form_id);

        exit;
    }


    public function test2($form_id)
    {

        // 初始化客户端
        $client = new AntCloudClient(
            "https://openapi.antchain.antgroup.com/gateway.do",
            "LTAI5tNciJJufZqWRs6tTpP6",
            "q5p5FA6gvXg49aae04QLUSQ8JGPnLZ"
        );

        // 构建请求
        $request = array(
            "app_did" => "did:mychain:19c3051eba145e47e92209bf9d9ddcdf6cb7b1ad4c24b6991a4e85e4bfe8f59b",
            "biz_index_key_value" => $form_id,
            "schema_name" => "testTwo",
            "method" => "blockchain.appex.solution.fastnotary.query",
            "version" => "1.0",
            "product_instance_id" => "appex",
            "region_name" => "CN-HANGZHOU-FINANCE",
        );

        // 发送调用请求，解析响应结果
        $response = $client->execute($request);
        //echo "<pre>";
        //print_r($response);
        $gg = $response['notaryRecord']['qrCodeUrl'];
        //var_dump($response);
        if ($gg) {
            $this->qrcode($gg, $form_id);
            $cover['path'] = '/uploads/image/' . $form_id . '.png';
            $cover['status'] = 1;
            $cover['create_time'] = time();
            $re = db('picture')->insertGetId($cover);
            if ($re) {
                db('app_form')->where(['id' => $form_id])->update(['qkl' => $re]);
                $src = "http://" . $_SERVER['HTTP_HOST'] . db('picture')->where("id=$re")->value('path');
                return apireturn(1, '成功', $src);
            }
        } else {
            return apireturn(2, '失败');
        }

        exit;
    }


    public function qrcode($text, $form_id)
    {
        $matrixPointSize = 12;
        $errorCorrectionLevel = 'L';
        $outfile = 'uploads/image/' . $form_id . '.png';
        vendor('qr_code');
        $objj = new \Qrcode;

        //vendor('phpexcel/PHPExcel');
        //3.实例化PHPExcel类
        //$objPHPExcel = new \PHPExcel();

        //var_dump($objj);exit;
        return $objj->png($text, $outfile, $errorCorrectionLevel, $matrixPointSize, 1);
    }

    public function qrcode729($text, $form_id)
    {
        $matrixPointSize = 12;
        $errorCorrectionLevel = 'L';
        $outfile = 'uploads/image/' . $form_id . '.png';

        $objj = new \QRcode;
        return $objj->png($text, $outfile, $errorCorrectionLevel, $matrixPointSize, 1);
    }


    //判断之前表单有没有盖章没上传图片的
    public function check()
    {
        $form_id = $_POST['form_id'];
        if (!$form_id) {
            return apireturn(2, '对象ID不能为空');
        }
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '对象ID不能为空');
        }

        $company_id = $_POST['company_id'];
        $condition['company_id'] = $company_id;


        //用章完成未上传图片
        $condition['status'] = array('eq', 5);
        $condition['uid'] = $uid;
        $condition['used_img'] = null;
        $res = db('app_form')->where($condition)->find();
        if ($res) {
            return apireturn(2, '有盖章未完上传照片的表单');
        } else {
            return apireturn(1, '成功');
        }
    }

    //审批类型详情
    public function splx_detail()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '对象ID不能为空');
        }
        $info = db('approval')->where(['id' => $id])->find();
        $info['status'] = $info['status'] - 1;
        $info['is_free'] = $info['is_free'] - 1;
        if ($info) {
            return apireturn(1, '成功', $info);
        } else {
            return apireturn(2, '失败');
        }
    }

    public function splx_bc()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '对象ID不能为空');
        }
        $data = $_POST;
        $res = db('approval')->where(['id' => $id])->update($data);
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    //发送短信
    public function send_sms($mobile = '')
    {
        $input = $_POST;
        if (empty($mobile)) $mobile = $input['phone'];

        //获取手机号
        $pattern = "/^1[123456789]\d{9}$/";
        if (empty($mobile)) {
            return apireturn(2, '请输入手机号');
        } else {
            if (preg_match($pattern, $mobile)) {

                $result = db('sms_code')->where(array('phone' => $mobile))->order('create_time desc')->find();
                $result = time() - $result['create_time'];
                if ($result < 60 and $result > 0) {
                    return apireturn(2, '当前手机号操作频繁,请60秒后发送');
                }
                $authnum = rand(100000, 999999);
                $statusStr = array(
                    "0" => 1,
                    "-1" => "参数不全",
                    "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
                    "30" => "密码错误",
                    "40" => "账号不存在",
                    "41" => "余额不足",
                    "42" => "帐户已过期",
                    "43" => "IP地址限制",
                    "50" => "内容含有敏感词"
                );
                $smsapi = "http://api.smsbao.com/";
                $user = 'tcwl';                                                     //短信平台帐号
                $pass = md5('tcwladmin.');                                          //短信平台密码
                $content = "【湖南同创未来管理咨询有限公司】尊敬的用户您的验证码为" . $authnum . "如非本人操作，请忽略。";//要发送的短信内容
                $phone = $mobile;                                                   //要发送短信的手机号码
                $sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $phone . "&c=" . urlencode($content);
                $result = file_get_contents($sendurl);
                if ($result == 0) {
                    $info['code'] = $authnum;
                    $info['phone'] = $phone;
                    $info['create_time'] = time();
                    $info['failure_time'] = time() + 600;//失效时间：10分钟
                    db('sms_code')->insert($info);
                    return apireturn(1, '短信发送成功', $authnum);
                } else {
                    return apireturn(2, $statusStr[$result]);
                }
            } else {
                return apireturn(2, '手机号码格式错误');
            }
        }
    }

    public function save_img()
    {
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID不能为空');
        }
        $img = $_POST['imgid'];
        if (!$img) {
            return apireturn(2, '对象ID不能为空');
        }
        $res = db('user')->where(['id' => $uid])->update(['img' => $img]);
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }

    }

    //判断上一次用章有没有完成
    public function again_use()
    {

        $form_id = $_POST['form_id'];
        if (!$form_id) {
            return apireturn(2, '对象ID不能为空');
        }
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '用户ID不能为空');
        }
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '用户ID不能为空');
        }

        $condition['company_id'] = $company_id;
        //用章完成未上传图片
        // $condition['status']=array('eq',4);//审核完成
        // $condition['status']=array('eq',5);//用章完成，未上传图片或者上传图片未超过24小时
        $condition['status'] = array('between', "4,5");
        $condition['used_img'] = null;
        $condition['uid'] = $uid;
        $condition['id'] = array('lt', $form_id);

        $res = db('app_form')->where($condition)->find();
        if ($res) {
            return apireturn(2, '有未完成的盖章');
        } else {
            return apireturn(1, '成功');
        }
    }

    public function cc()
    {
        $list = db('user')->field('id')->select();
        foreach ($list as $k => $v) {
            db('auth_group_access')->insert(['uid' => $v['id'], 'group_id' => 1]);
        }
    }

    //index实时刷新status
    public function show_status()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID不能为空');
        }
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '会员ID不能为空');
        }
        $status = db('staff')->where(['company_id' => $company_id, 'uid' => $uid])->value('status');
        if ($status) {
            $data['status'] = $status;
            $time = db('company_introduction')->where(['id' => $company_id])->value('service_expiration_time');
            if ($time > time()) {
                $data['gq'] = 1;//正常
            } else {
                $data['gq'] = 2;//企业锁定
            }

            return apireturn(1, '成功', $data);
        } else {
            return apireturn(2, '失败');
        }
    }

    //判断是不是自由审批
    public function is_free()
    {
        $id = $_POST['id'];
        if (!$id) {
            return apireturn(2, '对象ID不能为空');
        }
        $is_free = db('approval')->where(['id' => $id])->value('is_free');
        return apireturn(1, '成功', $is_free);
    }

    public function select_approver123()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apiReturn(2, '公司ID为空');
        }


        $condition['a.company_id'] = $company_id;
        $_POST['username'] ? $condition['b.username'] = $_POST['username'] : '';


        $condition['c.is_approver'] = 2;//是审批人才可以
        $list = db('staff')->alias('a')->join('user b', 'a.uid=b.id', 'LEFT')->join('position c', 'a.position_id=c.id', 'LEFT')->group('uid')->where($condition)->field('a.*')->select();
        //print_r($list);die;
        foreach ($list as $k => $v) {
            // print_r($v['uid']);die;
            $list[$k]['name'] = db('user')->where(['id' => $v['uid']])->value('username');
            $list[$k]['mobile'] = db('user')->where(['id' => $v['uid']])->value('mobile');

            if ($v['department_id']) {
                $a = explode(',', $v['department_id']);
                foreach ($a as $kk => $vv) {
                    if ($kk == 0) {
                        $partment = db('department')->where(['id' => $vv])->value('name');
                    } else {
                        $partment .= ',' . db('department')->where(['id' => $vv])->value('name');
                    }

                }

            }
            $list[$k]['department_list'] = $partment;


        }
        $list = array_merge($list);
        if ($list) {
            return apireturn(1, '成功', $list);
        } else {
            return apireturn(2, '暂无数据', []);
        }
    }

    public function choose_approver123()
    {
        $app_id = $_POST['app_id'];
        if (!$app_id) {
            return apireturn(2, '审批类型ID为空');
        }
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '选择的用户ID为空');
        }


        $uname = db('user')->where(['id' => $uid])->value('username');
        return apireturn(1, '成功', $uname);

    }

    //异常处理
    public function abnormal()
    {
        $app_id = $_POST['app_id'];
        if (!$app_id) {
            return apireturn(2, '对象ID不能为空');
        }
        $data['reason'] = 3;
        $data['app_id'] = $app_id;
        $info = db('app_form')->where(['id' => $app_id])->find();
        $data['seal_id'] = $info['seal_id'];
        $data['uid'] = $info['uid'];
        $data['company_id'] = $info['company_id'];
        $data['lat'] = $info['lat'];
        $data['lng'] = $info['lng'];
        $data['create_time'] = time();
        $res = db('alarm_record')->insert($data);
        if ($res) {
            //锁定账户
            db('staff')->where(['uid' => $data['uid'], 'company_id' => $data['company_id']])->update(['status' => 2]);
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    public function status_testing()
    {
        $uid = $_POST['uid'];
        $company_id = $_POST['company_id'];
        if (!$uid) {
            return apireturn(2, '用户ID不能为空');
        }
        if (!$company_id) {
            return apireturn(2, '公司ID不能为空');
        }
        $status = db('staff')->where(['uid' => $uid, 'company_id' => $company_id])->value('status');
        if ($status == 1) {
            return apireturn(1, '成功', $status);
        } else {
            return apireturn(2, '您的账户已锁定', $status);
        }

    }

    //服务费价格
    public function seal_price()
    {
        $seal_price = C('SEAL_PRICE');
        if (!$seal_price) {
            return apireturn(1, '暂未配置', '');
        } else {
            return apireturn(1, '成功', $seal_price);
        }
    }

    //支付
    public function pay()
    {
        $url = 'http://test-efps.epaylinks.cn/api/txs/pay/WxJSAPIPayment';
        $openid = 'oZGwz5J06QXflrPFDp-5i3eoJXg4';
        $data = [
            'version' => '3.0',
            'outTradeNo' => 'yz1641784472',//'商户订单号'
            'customerCode' => '',//'商户编号'
            'appId' => 'wxbc7aca851ac61a98',//商户微信公众号的 APPID(我现在是小程序的APPID)
            'openId' => $openid,//用户在appId下的唯一标识(我现在是小程序下的openid)
            'clientIp' => '',//用户访问商户系统服务端时的出口IP    选填
            'orderInfo' => [
                'Id' => 1,//商品订单编号
                'businessType' => 100002,//业务种类  我选的虚拟商品购买
                'costPrice' => '',//订单原价         选填
                'receiptId' => '',//商品小票 ID      选填
                'goodsTag' => '',//微信订单优惠标记   选填
                'goodsList' => [
                    'goodsId' => 1,//商品ID         选填
                    'name' => '印章',//商品名称
                    'price' => 1,//单价  分         选填
                    'number' => 1,//商品数量
                    'amount' => 1,//商品金额 分
                    'category' => '',//商品类目       选填
                    'remark' => '',//说明            选填

                ],
            ],//商品订单信息
            'payAmount' => 1,//订单金额
            'payCurrency' => 'CNY',//支付币种
            'payMethod' => '35',//支付方式
            'noCreditCards' => false,//是否禁止信用卡支付
            'notifyUrl' => "http://" . $_SERVER['HTTP_HOST'] . '/index/app/payment_callback',//异步通知地址
            'locationToken' => '',//授权 token                     选填
            'attachData' => '',//附加数据                          选填
            'transactionStartTime' => date('YmdHis'),//交易开始时间
            'transactionEndTime' => '',//交易超时时间               选填
            'channelMchtNo' => '',//上游商户号                      选填
            'nonceStr' => 'pay' . rand(100, 999),//32 个字符的随机字符串，用于保证签名不可预测
        ];
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        httpsRequest($url, $data);
    }

    //支付回调
    public function payment_callback()
    {
        $notice_info = json_decode(file_get_contents('php://input'), true);
        //file_put_contents(RUNTIME_PATH . 'infoNoticeSupplier123.txt', $notice_info['sub_mch_code']);
        file_put_contents('121.txt', $notice_info);
    }

    public function add_order()
    {
        $data['uid'] = $_POST['uid'];
        $data['company_id'] = $_POST['company_id'];
        $data['order_number'] = $_POST['order_number'];
        $res = db('order')->insert($data);
        if ($res) {
            return apireturn(1, '成功');
        } else {
            return apireturn(2, '失败');
        }
    }

    //续费
    public function renew7788()
    {
        $input = Request()->post();

        $company_id = $input['company_id'];
        if (!$company_id) {
            return apireturn(2, '公司ID不能为空');
        }

        $market_user_id = db('company_introduction')->where(['id' => $company_id])->value('market_user_id');
        $device_count = db('seal')->where(['company_id' => $company_id])->count();
        //print_r($market_user_id);die;
        $time = time();
        $auth_data = [
            md5('2s0e2a1lD_amvaerakpeit' . date('Y/m/d')) => md5(date('Y/m/d') . '9a950aa3ef6d130d'),
            'timestamp' => $time,
            'company_id' => $company_id,
            'market_user_id' => $market_user_id,
            'device_count' => $device_count,
            'device_single_price' => C('SEAL_PRICE'),
        ];
        $auth_result = httpsRequest('https://zssw.hnwcft.com' . '/Index/Auth/getSign', $auth_data);
        $auth_result = json_decode($auth_result, true);
        //return $auth_result['data'];
        if ($auth_result['result'] == 1) {

            $a = md5('2s0e2a1lD_amvaerakpeit' . date('Y/m/d'));
            $b = md5(date('Y/m/d') . '9a950aa3ef6d130d');
            $data[$a] = $b;
            $data['sign'] = md5($auth_result['data'] . ($time + 3));
            $bb = httpsRequest('https://zssw.hnwcft.com' . '/Index/Auth/yearService', $data);
            $cc = json_decode($bb, true);
            if ($cc['result'] == 1) {
                //续费成功+1年
                $time = db('company_introduction')->where(['id' => $company_id])->value('service_expiration_time');
                if ($time > time()) {
                    //过期时间大于现在，就在过期时间上延长
                    $service_expiration_time = strtotime("+1year", $time);
                } else {
                    //过期时间小于于现在，就在现在的时间上延长
                    $service_expiration_time = strtotime("+1year");
                }
                db('company_introduction')->where(['id' => $company_id])->update(['service_expiration_time' => $service_expiration_time]);
            }
            return $bb;
        }

    }

    //解绑微信
    public function unbind()
    {
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '会员ID不能为空');
        }
        $res = db('user')->where(['id' => $uid])->update(['openid' => '', 'app_openid' => '', 'unionid' => '']);
        if ($res) {
            $info['openid'] = '';
            return apireturn(1, '成功', $info);
        } else {
            return apireturn(2, '失败');
        }
    }

    public function select_approver721()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apiReturn(2, '公司ID为空');
        }


        $condition['a.company_id'] = $company_id;

        $where['company_id'] = $company_id;
        $_POST['username'] ? $where['name'] = array('like', "%$_POST[username]%") : '';
        $department_list = db('department')->where($where)->field('id')->select();


        if ($_POST['username']) {
            $condition['b.username|b.account'] = array('like', "%$_POST[username]%");
        }

        $condition['c.is_approver'] = 2;//是审批人才可以

        $list1 = db('staff')->alias('a')->join('user b', 'a.uid=b.id', 'LEFT')->join('position c', 'a.position_id=c.id', 'LEFT')->group('uid')->where($condition)->field('a.*')->select();

        // print_r($staff_list);die;
        $list = array_merge($list1);
        // $list=array_unique($list2);
        $u = $_POST['u'];
        $uu = explode(',', $u);
        //print_r($uu);die;
        foreach ($list as $k => $v) {
            if (in_array($v['uid'], $uu)) {
                $list[$k]['sort'] = array_search($v['uid'], $uu) + 1;
                $list[$k]['ck'] = 1;

            } else {
                $list[$k]['sort'] = '';
                $list[$k]['ck'] = '';
            }

            $list[$k]['name'] = db('user')->where(['id' => $v['uid']])->value('username');
            $list[$k]['mobile'] = db('user')->where(['id' => $v['uid']])->value('mobile');

            if ($v['department_id']) {
                $a = explode(',', $v['department_id']);
                foreach ($a as $kk => $vv) {
                    if ($kk == 0) {
                        $partment = db('department')->where(['id' => $vv])->value('name');
                    } else {
                        $partment .= ',' . db('department')->where(['id' => $vv])->value('name');
                    }

                }

            }
            $list[$k]['department_list'] = $partment;

        }
        $list = array_merge($list);
        if ($list) {
            return apireturn(1, '成功', $list);
        } else {
            return apireturn(2, '暂无数据', []);
        }
    }

    public function u()
    {
        $company_id = $_POST['company_id'];
        if (!$company_id) {
            return apiReturn(2, '公司ID为空');
        }

        $u = $_POST['u'];
        $condition['a.company_id'] = $company_id;

        $where['company_id'] = $company_id;
        $_POST['username'] ? $where['name'] = array('like', "%$_POST[username]%") : '';
        $department_list = db('department')->where($where)->field('id')->select();


        if ($_POST['username']) {
            $condition['b.username|b.account'] = array('like', "%$_POST[username]%");
        }

        $condition['c.is_approver'] = 2;//是审批人才可以

        $list1 = db('staff')->alias('a')->join('user b', 'a.uid=b.id', 'LEFT')->join('position c', 'a.position_id=c.id', 'LEFT')->group('uid')->where($condition)->field('a.*')->select();

        // print_r($staff_list);die;
        $list = array_merge($list1);
        //$list=array_unique($list2);

        // $u_list=explode(',', $_POST['u_list']);

        $uu = explode(',', $u);
        foreach ($list as $k => $v) {
            if (in_array($v['uid'], $uu)) {
                $list[$k]['sort'] = array_search($v['uid'], $uu) + 1;
                $list[$k]['ck'] = 1;

            } else {
                $list[$k]['sort'] = '';
                $list[$k]['ck'] = '';
            }

            $list[$k]['name'] = db('user')->where(['id' => $v['uid']])->value('username');
            $list[$k]['mobile'] = db('user')->where(['id' => $v['uid']])->value('mobile');

            if ($v['department_id']) {
                $a = explode(',', $v['department_id']);
                foreach ($a as $kk => $vv) {
                    if ($kk == 0) {
                        $partment = db('department')->where(['id' => $vv])->value('name');
                    } else {
                        $partment .= ',' . db('department')->where(['id' => $vv])->value('name');
                    }

                }

            }
            $list[$k]['department_list'] = $partment;

        }
        $list = array_merge($list);
        if ($list) {
            return apireturn(1, '成功', $list);
        } else {
            return apireturn(2, '暂无数据', []);
        }
    }

    public function choose_approver456()
    {
        $app_id = $_POST['app_id'];
        if (!$app_id) {
            return apireturn(2, '审批类型ID为空');
        }
        $uid = $_POST['uid'];
        if (!$uid) {
            return apireturn(2, '选择的用户ID为空');
        }
        $u_list = explode(',', $uid);
        foreach ($u_list as $k => $v) {
            $sh .= '/' . db('user')->where(['id' => $v])->value('username');
        }
        $uname = substr($sh, 1);
        // $uname=db('user')->where(['id'=>$uid])->value('username');
        return apireturn(1, '成功', $uname);

    }
}
